Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return variable from node.js to sh script

Tags:

bash

node.js

sh

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}
like image 532
MrBinWin Avatar asked Feb 18 '15 11:02

MrBinWin


1 Answers

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[@]}";
like image 154
bgoldst Avatar answered Nov 04 '22 00:11

bgoldst