Here’s a convenient pattern for anyone doing Bash scripting: Use a subshell with the Bash halt-on-failure feature enabled to execute a set of commands but break as soon as any one of them fails.
1 2 3 4 5 6 7 8 |
( set -e # Enable halt-on-failure true echo foo false echo bar echo baz ) |
The above example will print only “foo” because the false command returns a non-zero error code which causes the subshell to exit.
For quick and simple scripts it’s easy to just enable the halt-on-failure feature at the beginning of the entire script, but for anything more advanced, you want to be able to “catch” the error and handle it in a more sophisticated way.
Another similar mechanism that Bash provides is a way to run a command or function when the script exits:
1 2 3 4 |
function finish { # Your cleanup code here } trap finish EXIT |
This is also a great way to make your Bash scripts more robust, but is best reserved for standard cleanup, like removing temporary files that may have been created.