38

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 ?

3
  • You can't return a value from a script, your example is just calling a function and the return value is thrown away because it does nothing... Commented Apr 2, 2017 at 13:44
  • the test is returned to the main and it isn't printed to the output, so here is nothing to capture... You need output the returned value... Commented Apr 2, 2017 at 13:46
  • What you guyz are saying makes sense. However, how do I go about capturing what was printed by the node script into a BASH variable ? Commented Apr 2, 2017 at 13:48

2 Answers 2

53

@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
Sign up to request clarification or add additional context in comments.

5 Comments

what if I'm also using console log in the function? And I want the returning value, not all the console log values?
@MoroSilverio Could you write the output from the function to a file then read the file from Bash?
@DoomGoober That should be an answer
The answer is wrong. If your Node script contains multiple console.logs $val will have the value of all those console.logs. This is not what the OP requested. console.logs inside the script should be ignored and $val should only contain the value of the return statement
@Kawd The OP accepted the answer, so probably it is helpful for him. Maybe he knows better what he requested. :D You can also use filtering on the bash level, for example val=$(node app.js | grep 'test') for get only lines containing the test string and so on... Zilion possibilities..
9

You can write output to the stdout with process.stdout.write

b.sh file:

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

app.js file:

#!/usr/bin/env node
function f() {
  return "test";
}
process.stdout.write(f());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.