0

I have this line in a bash script:

$ node $(node `dirname $0`/foo.js) "$@"  

In foo.js, I have

if(x){
process.exit(0);
}
else{
process.exit(1);
}

I want the bash script to abort / error out, if the process defined by

$(node `dirname $0`/foo.js)

exits with a non-zero exit code.

How can I do this?

2 Answers 2

2

Update

If you want to capture the exit code of the command substitution, assign the output to a variable. The assignment doesn't change the $?, so it still contains the status of the substitution.

output=$(node ...)
status=$?
(( status )) && exit 1

Original reply

You can check the exit code with $?:

node ...
(( $? )) && exit $?

Or, you can use it directly in a condition:

if ! node ... ; then exit 1 ; fi

Or, just tell bash to exit on error:

set -e
node ...

Use set +e to restore the normal behaviour if needed.

Sign up to request clarification or add additional context in comments.

7 Comments

can you edit your answer to include the $(node) instead of just node, I feel like that does make a difference? (at least when reading your answer)
for example, "if ! $(node foo.js) ; then exit 1 ; fi", is probably totally different than "if ! node ... ; then exit 1 ; fi", I need to capture the stdout from the node foo.js process
Oh wait, you want to exit if the command substitution fails? Then assign the output to a variable: output=$(node ...), the $? then holds the exit status of the command substitution.
@choroba do you have any idea why we can't use this technic with local variables? If I do so status is always equal to 0.
@klefevre: You need to declare the local variable before assigning to it, i.e. local output; output=$(...)
|
0

The way I would tackle this problem is to add this line before the full command is run:

$(node `dirname $0`/foo.js); rc="$?"; if [ "$rc" -ne 0 ]; then exit; fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.