Thursday, October 20, 2011

Terminating scripts when any individual command fails

Let’s say you have a script that builds a project, runs all tests, and pushes the binary to a staging/production server.  If the build fails or a test fails you’d want the script to stop immediately.  Pushing a binary that failed some tests is obviously wrong.  You can check for a command’s return value using if and terminate your script.  But doing that for every command in the script would make your script less readable and more prone to bugs.

Shells provide a clean solution for this use case: you can set a script-level option to stop the script execution if any command you invoke from the script exits with a non-zero status.  You do that in bash using
set -e
and in zsh using
setopt err_exit
So your script would essentially look like this:
#!/bin/bash
set -e
make
make test
make push
zsh also has a err_return option that can be set to make a function return (as opposed to terminating the whole script) when a command invoked by a function fails.

No comments:

Post a Comment