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
If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:
Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.
Run it with
-e
orset -e
at the top.Also look at
set -u
.just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:
which is the same as
cmd || exit errcode
as someone showed.eg. I want to make sure a partition is unmounted if mounted: