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

Issue

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

Solution

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.

Answered By – chepner

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published