Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating bash "&&" exit codes behaviour

We had a recent experience with bash that even we found a solution, it keeps twisting my mind. How does bash evaluates the && expression in terms of return codes?

Executing this script, that should fail because myrandomcommand does not exist:

#!/bin/bash

set -e

echo "foo"
myrandomcommand
echo "bar"

The result is the expected one:

~ > bash foo.sh 
foo
foo.sh: line 6: myrandomcommand: command not found
[exited with 127]
~ > echo $?
127

But changing slightly the code using the && expression:

#!/bin/bash

set -e

echo "foo"
myrandomcommand && ls
echo "bar"

The ls statement is not executed (since the first statement fails and does not evaluate the second statement), but the script behaves very different:

~ > bash foo.sh 
foo
foo.sh: line 6: myrandomcommand: command not found
bar                  # ('bar' is printed now)
~ > echo $?
0

We found out that using the expression between parenthesis (myrandomcommand && ls) it works as expected (like the first example), but I would like to know why.

like image 520
jaume Avatar asked Jun 15 '16 14:06

jaume


1 Answers

You can read in the man pages of bash:

-e   Exit  immediately if a simple command (see SHELL GRAMMAR above) exits with a
     non-zero status. The shell does not exit if the command that fails is part of the
     command list immediately following a while or until keyword, part of the test in
     an if statement, part of a && or || list, or if the command's return value is being
     inverted via !.  A trap on ERR, if set, is executed before the shell exits.
like image 99
Jdamian Avatar answered Oct 13 '22 23:10

Jdamian