A technical blog written by Richard Paul

Failing Early in Bash

We use a bash script to automate deployment to our live servers, today it didn’t go so well. Drilling into the problem it appeared one of the copy commands failed due to permissions but the deployment continued anyway and we didn’t notice.

Bash provides a handy feature which will stop the script if any of the commands fail (return a non-zero value).

set -o errexit

Here you can see a simple example

set -o errexit  ## exit after any error (non-zero statement) 
echo before failing command
mkdir a/b
echo after failing command

Without this toggle enabled the script would have quite happily failed to create directory a/b then continued on with the rest of the script printing out after failing command. With the toggle enabled the script stops after it fails to create the directory.

before failing command
mkdir: cannot create directory `a/b': No such file or directory

Obviously in this trivial example it doesn’t seem important, but when an essential part of your deployment fails you want to know about it immediately.

Further reading available at: http://www.davidpashley.com/articles/writing-robust-shell-scripts.html