Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a return value from a node script in BASH?

Tags:

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 ?

like image 219
Attilah Avatar asked Apr 02 '17 13:04

Attilah


People also ask

Can we return value from 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.

How do I check the return value of a program in Linux?

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.

How do I run a node script in terminal?

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.


1 Answers

@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 
like image 125
jm666 Avatar answered Sep 23 '22 16:09

jm666