Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading