Home > Net >  Bash script does not catch error status with `set -e`
Bash script does not catch error status with `set -e`

Time:07-09

Could someone explain please why the following simple script does not terminate on error status?

I would expect that false would return with error status and cause the script to stop as I use set -e

set -e
false && true
echo $?
echo Done

Output:

1
Done

while this one does:

set -e
false
echo $?
echo Done

Output is empty

CodePudding user response:

Your expectation is incorrect, and a big reason why set -e isn't really recommended. There is a long list of exceptions (including &&) to the rule that set -e exits on a non-zero exit status, precisely because not all non-zero exit statuses indicate an error, but simply a negative result. grep, for example, has a non-zero exit status simply to indicate that no match was found.

echo foo | grep bar && echo "Found bar"
echo foo | grep bar || echo "bar not found"

The assumption is that if you are examining the exit status of a command for any reason (if, ||, &&, etc), then you are expecting the possibility of failure and it's not an error if it does.

  • Related