views:

178

answers:

4

Hi,

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:

#!/bin/bash  

cd some_dir  

./configure --some-flags  

make  

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 afterward 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?

+1  A: 

One idiom is:

cd some_dir && ./configure --some-flags && make && make install

I realize that can get long, but for larger scripts you could break it into logical functions.

Matthew Flaschen
glenn jackman
+2  A: 

I think that what you are looking for is the trap command:

trap command signal [signal ...]

For more information, see this page - you have to scroll down a little way to where it says "Setting traps".

Another option is to use the set -e command at the top of your script - it will make the script exit if any program / command returns a non true value.

a_m0d
+1  A: 

To exit the script as soon as one of the commands failed, add this at the beginning:

set -e

This causes the script to exit immediately when some command that is not part of some test (like in a if [ ... ] condition or a && construct) exits with a non-zero exit code.

sth
+2  A: 

Use the set -e builtin:

#!/bin/bash
set -e
# Any subsequent commands which fail will cause the shell script to exit immediately

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

#!/bin/bash -e
# Any subsequent commands which fail will cause the shell script to exit immediately

You can also remove this behavior with set +e.

Adam Rosenfield