How to get the JavaScript variable value in the bash script?

Viewed 31

I have a Javascript file with the below code snippet :

var test = "printValueInBashScript"

I have a bash script with the below snippet :

#!/bin/bash
node app.js
echo "test :: ${test}" #I know this is wrong

I want the test value coming from the js file app.js to be fetched in the bash script. As you can see I am running the app.js using node in bash. How can I store the test variable value of JS in the bash script so that I can use it for further processing?

1 Answers

You can print the value, then capture the output in bash:

// test.js
const test1 = "printValueInBashScript";
console.log(test1);

// test.sh
test="$(node test.js)"
echo "test :: ${test}"

If you need to set multiple variables, you can have the app print the bash function declarations, which you then execute. This method is convenient, but less safe (obviously, you have to have trust in the code you are executing not to print anything malicious). It is used, for example, by ssh-agent. This is how it looks like:

// test.js
const test1 = "printValueInBashScript";
const test1 = "printAnotherValueInBashScript";
console.log(`test1="${test1}"`);
console.log(`test2="${test2}"`);

// test.sh
eval "$(node test.js)"
echo "test1 :: ${test1}"
echo "test2 :: ${test2}"
Related