I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?
|
After each command, the exit code can be found in the
You need to be careful of piped commands since the
will not return an error code if the file doesn't exist (since the |
|||||||||||||||||||||
|
If you want to work with $?, you'll need to check it after each command, since $? is updated after each command exits. This means that if you execute a pipeline, you'll only get the exit code of the last process in the pipeline. Another approach is to do this:
If you put this at the top of the shell script, it looks like bash will take care of this for you. As a previous poster noted, "set -e" will cause bash to exit with an error on any simple command. "set -o pipefail" will cause bash to exit with an error on any command in a pipeline as well. See here or here for a little more discussion on this problem. Here is the bash manual section on the set builtin. |
|||||
|
" |
|||||||||
|
http://cfaj.freeshell.org/shell/cus-faq-2.html#11
|
||||
|
for bash:
|
|||||||||||||
|
If you just call exit in the bash with no parameters, it will return the exit code of the last command. Combined with OR the bash should only invoke exit, if the previous command fails. But I haven't tested this. command1 || exit; command2 || exit; The Bash will also store the exit code of the last command in the variable $?. |
|||
|
|
|||||
|
In bash this is easy, just tie them together with &&:
You can also use the nested if construct:
|
|||
|
|
||||
|