Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell scripting: die on any error

Suppose a shell script (/bin/sh or /bin/bash) contained several commands. How can I cleanly make the script terminate if any of the commands has a failing exit status? Obviously, one can use if blocks and/or callbacks, but is there a cleaner, more concise way? Using && is not really an option either, because the commands can be long, or the script could have non-trivial things like loops and conditionals.

like image 871
Pistos Avatar asked Dec 15 '08 15:12

Pistos


2 Answers

With standard sh and bash, you can

set -e

It will

$ help set
...
        -e  Exit immediately if a command exits with a non-zero status.

It also works (from what I could gather) with zsh. It also should work for any Bourne shell descendant.

With csh/tcsh, you have to launch your script with #!/bin/csh -e

like image 109
mat Avatar answered Oct 17 '22 07:10

mat


May be you could use:

$ <any_command> || exit 1
like image 23
Barun Avatar answered Oct 17 '22 07:10

Barun