Assessing the behavior of bash codes "&&"

We had recent experience with bash that even we found a solution, it continues to meander. How does bash evaluate the && expression in terms of return codes?

Running this script, which should fail, since myrandomcommand does not exist:

 #!/bin/bash set -e echo "foo" myrandomcommand echo "bar" 

The result is the expected:

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

But slightly changing the code with 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 in a completely different way:

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

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

+6
source share
1 answer

You can read on the bash manual pages:

 -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 return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. 
+8
source

All Articles