a little madness

A man needs a little madness, or else he never dares cut the rope and be free -Nikos Kazantzakis

Zutubi

Bash Tip: Exit on Error

Back in my post Your Next Programming Language I mentioned I would post occassional tips about bash scripting. As soon as I started writing my next script, it occured to me: the first thing I always do when writing a new bash script is set the errexit option:

set -e

This option makes your script bail out when it detects an error (a command exiting with a non-zero exit code). Without this option the script will plough on, and mayhem often ensues. In all the noise generated it can be a pain to found the root cause of the problem. So I make it a rule to set this option and fail as early as possible.


Into continuous integration? Want to be? Try pulse.

Liked this post? Share it!

6 Responses to “Bash Tip: Exit on Error”

  1. September 24th, 2009 at 4:52 am

    Yassine says:

    Thank you for this tip. Very helpful

  2. August 3rd, 2011 at 4:31 am

    Jens Alfke says:

    Thanks for taking a minute to post this tip — I’m embarrassingly n00bish about shell scripting but have to maintain some build scripts, and was trying to figure out how to do this so I don’t miss errors. Fortunately I composed a good enough google search that your post came up in 2nd place and saved my day.

  3. September 24th, 2011 at 6:42 am

    adminPL says:

    great tip – thanks ?

  4. October 22nd, 2011 at 1:52 am

    Eric says:

    Thanks it helps a lot !!!!

  5. April 24th, 2013 at 8:50 pm

    Jay says:

    What to do if the exit-on-error is mixed with the opposite. That is, sometimes I need exit on error, sometimes I don’t Want to exit if the return value is not 0.
    For example, if egrep does not find the pattern in a given string, it returns 1. In this case I don’t want to exit.

    A simple solution is to guard the statement with set +e and set -e. But this will make the scripts looking messy.

    Is there a better idea?

  6. May 2nd, 2013 at 12:35 pm

    Jason says:

    One way would be to add “|| true” to the end of commands that you don’t care about the exit code of. So:

    egrep ‘[a-z]+’ myfile.txt || true

Leave a Reply