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 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?
One idiom is:
I realize that can get long, but for larger scripts you could break it into logical functions.
Here is how to do it:
To exit the script as soon as one of the commands failed, add this at the beginning:
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.Use the
set -e
builtin:Alternatively, you can pass
-e
on the command line:You can also disable this behavior with
set +e
.(*) Note:
(from
man bash
)I think that what you are looking for is the
trap
command:For more information, see this page.
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.Use it in conjunction with
pipefail
.-e (errexit): Abort script at first error, when a command exits with non-zero status (except in until or while loops, if-tests, list constructs)
-o pipefail: Causes a pipeline to return the exit status of the last command in the pipe that returned a non-zero return value.
Chapter 33. Options