linuxbashunixshell

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


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

Solution

  • 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 manual on the "set" internal command for more details.

    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. I personally start almost all portable shell scripts with set -e.

    If I'm working with bash specifically, I'll start with

    set -Eeuo pipefail
    

    This covers more error handling in a similar fashion. I consider these as sane defaults for new bash programs. Refer to the bash manual for more information on what these options do.