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:
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.
This entry was posted on Wednesday, May 24th, 2006 at 1:37 pm and is filed under Bash, Project Automation, Technology. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

September 24th, 2009 at 4:52 am
Yassine says:Thank you for this tip. Very helpful
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.
September 24th, 2011 at 6:42 am
adminPL says:great tip – thanks ?
October 22nd, 2011 at 1:52 am
Eric says:Thanks it helps a lot !!!!
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?
May 2nd, 2013 at 12:35 pm
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