radman radman - 2 years ago 120
Bash Question

Automatic exit from bash shell script on error

I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:


cd some_dir

./configure --some-flags


make install

So in this case if the script can't change to the indicated directory then it would certainly not want to do a ./configure afterwards if it fails.

Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?

Answer Source

Use the set -e builtin:

set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately

Alternatively, you can pass -e on the command line:

bash -e my_script.sh

You can also disable this behavior with set +e.

(*) Note:

The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or || list, or if the command's return value is being inverted via !

(from man bash)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download