Failure in a bash script usually means failure of the script

So, when you write a bash script that does a certain amount of tasks for you, but you don’t want the script to keep running after some command inside the script failed, simply add a line to the script.

set -e

Quoting the man page:

-e errexit

Exit immediately if a simple command exits with a non-zero, unless the command that fails is part of an until or loop, part of an if statement, part of a && or || list, if the command’s return is being inverted using !.

If you want to reset to normal behaviour, reverse it using:

set +e

Very useful, it’ll save you lot of tedious if’s and error checking.

One Comment

  • Cheatah wrote:

    Some people tend to use #! /bin/sh -e for this purpose, but using set -e is much more elegant. This makes sure that the script is handled properly, even when called via sh /part/to/file.

    You might also want to use set -u which forces you to write robust code. In general, people who write bash scripts should know the set built-in command. It really helps writing better code and can help debugging.

    Do you know trap as well? If you combine -e and trap, you can use it like some sort of try/catch/finally construction and allows you to do some cleanup upon exit, e.g. remove lock files.

Leave a Reply

Your email is never shared.Required fields are marked *