I have a Bash shell script that invokes a number of commands. I would like to have the shell script automatically exit with a return value of 1 if any of the commands return a non-zero value.
Is this possible without explicitly checking the result of each command?
e.g.
dosomething1
if [[ $? -ne 0 ]]; then
exit 1
fi
dosomething2
if [[ $? -ne 0 ]]; then
exit 1
fi
Add this to the beginning of the script:
This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.
See the bash(1) man page on the "set" internal command for more details.
I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.
The if statements in your example are unnecessary. Just do it like this:
If you take Ville Laurikari's advice and use
set -e
then for some commands you may need to use this:The
|| true
will make the command pipeline have atrue
return value even if the command fails so the the-e
option will not kill the script.To add to the accepted answer:
Bear in mind that
set -e
sometimes is not enough, specially if you have pipes.For example, suppose you have this script
... which works as expected: an error in
configure
aborts the execution.Tomorrow you make a seemingly trivial change:
... and now it does not work. This is explained here, and a workaround (Bash only) is provided:
should suffice.
An expression like
will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":
The
$?
variable is rarely needed. The pseudo-idiomcommand; if [ $? -eq 0 ]; then X; fi
should always be written asif command; then X; fi
.The cases where
$?
is required is when it needs to be checked against multiple values:or when
$?
needs to be reused or otherwise manipulated: