MrBinWin
MrBinWin

Reputation: 1319

Return variable from node.js to sh script

Is it possible to execute node.js app from .sh script, return some variable and continue the .sh script? Something like:

#!/bin/sh
SOME_VARIABLE = node app.js
echo ${SOME_VARIABLE}

Upvotes: 10

Views: 8923

Answers (1)

bgoldst
bgoldst

Reputation: 35324

Firstly, ensure you're using bash, not sh, as there are significant differences in functionality between the two.

One simple solution is command substitution, although be aware that trailing newlines in the command output will be stripped. Also, when echoing, to protect the contents of the variable (such as spaces and glob characters) from metaprocessing by the shell, you have to double-quote it:

#!/bin/bash
output=$(node app.js);
echo "$output";

Another solution is process substitution in more recent versions of bash. You could even collect the output as an array of lines in this case:

#!/bin/bash
exec 3< <(node app.js);
lines=();
while read -r; do lines+=("$REPLY"); done <&3;
exec 3<&-;
echo "${lines[@]}";

Upvotes: 13

Related Questions