Linux – Aborting a shell script if any command returns a non-zero value

bashlinuxshellunix

I have a Bash shell script that invokes a number of commands.

I would like to have the shell script automatically exit with a return value of 1 if any of the commands return a non-zero value.

Is this possible without explicitly checking the result of each command?

For example,

dosomething1
if [[ $? -ne 0 ]]; then
    exit 1
fi

dosomething2
if [[ $? -ne 0 ]]; then
    exit 1
fi

Best Answer

Add this to the beginning of the script:

set -e

This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.

See the bash(1) man page on the "set" internal command for more details.

I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.