Exception Handling in Bash

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.

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:

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.

This entry was posted in Uncategorized. Bookmark the permalink.