When to use set -e

bash, shell

Solution

Yes, you should always use it. People make fun of Visual Basic all the time, saying it's not a real programming language, partly because of its “On Error Resume Next” statement. Yet that is the default in shell! `set -e` should have been the default. The potential for disaster is just too high.

In places where it's ok for a command to fail, you can use `|| true` or its shortened form `||:`, e.g.

grep Warning build.log ||:

In fact you should go a step further, and have

set -eu
set -o pipefail

at the top of every `bash` script.

`-u` makes it an error to reference a non-existent environment variable such as `${HSOTNAME}`, at the cost of requiring some gymnastics with checking `${#}` before you reference `${1}`, `${2}`, and so on.

`pipefail` makes things like `misspeled-command | sed -e 's/^WARNING: //'` raise errors.

Problem

I come across `set -e` a some time ago and I admit I love it. Now, after some time I'm back to write some bash scripting. My question is if there are some best practices when to use `set -e` and when not to use it (.e.g. in small/big scripts etc.) or should I rather use a pattern like `cmd || exit 1` to track errors?

Original source