Let's say I have a bash script that calls a node script. I've tried to do it like this:
b.sh file:
#!/bin/bash v=$(node app.js) echo "$v"
app.js file:
#!/usr/bin/env node function f() { return "test"; } return f();
How do I access the value returned by the node script ("test") from my bash script ?
Unlike functions in “real” programming languages, Bash functions don't allow you to return a value when called. When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure.
In Linux, run the program at the command prompt and then use the echo command to confirm the return value: $ echo $? At the command prompt in Windows, you must code a batch file to fish out the return value.
You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.
@Daniel Lizik gave an good answer (now deleted) for the part: how to output the value, e.g. using his answer:
#!/usr/bin/env node function f() { return "test"; } console.log(f())
And for the part how to capture the value in bash, do exactly as in your question:
#!/bin/bash val=$(node app.js) echo "node returned: $val"
the above prints:
node returned: test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With