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.

This entry was posted in Linux & BSD and tagged , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

2 Comments

  1. Cheatah
    Posted July 24, 2011 at 11:09 | Permalink

    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.

  2. Posted October 3, 2018 at 13:54 | Permalink

    Hello it’s me, I am also visiting this site regularly, this web site is actually pleasant and the users are in fact sharing nice thoughts.

    my web site; [?????](https://www.shuffle9.org “?????”)

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Subscribe without commenting