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.
+13
A:
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
mat
2008-12-15 15:43:34
Thanks, this seems to be what I want. I should sharpen my Google fu, I guess... :)
Pistos
2008-12-15 15:56:19
Note that commands in conditionals can fail without causing the script to exit - which is crucial. For example: if grep something /some/where; then : it was found; else : it was not found; fi works fine, regardless of whether something is found in /some/where.
Jonathan Leffler
2008-12-16 04:00:48