set -e Misses a Failure Inside a Pipeline Unless pipefail Is Set

In progress Linux

set -e makes a Bash script stop when a command fails, but a pipeline's exit status is the status of its last command. When an earlier stage fails and the last one succeeds, the pipeline succeeds and the script carries on with missing or empty data. set -o pipefail makes the pipeline fail when any stage fails, which is why bootstrap scripts start with set -euo pipefail.

What Each Option Catches

Option Stops the script when
-e (errexit) a simple command or a pipeline returns non-zero
-u (nounset) the script reads a variable that was never set, such as a mistyped name
-o pipefail any stage of a pipeline fails, not only the last one

A download written through tee shows the gap:

set -e
curl -fsS "$KEY_URL" | tee /etc/apt/keyrings/repo.asc   # curl fails, tee succeeds
apt-get update                                         # runs anyway, with an empty key file

With pipefail, the pipeline returns curl's error and the script stops on that line.

Where set -e Stays Silent Anyway

Bash deliberately ignores failures in some positions, with or without pipefail:

  • commands tested by if, while or until, and any function called from such a test;
  • commands on the left of && or ||, and commands negated with !;
  • local var=$(cmd) and export var=$(cmd): the status checked is that of local or export, not of cmd. Declare first, then assign (local var; var=$(cmd)).

Marking the Failures You Expect

Some commands may fail legitimately: deleting something already gone, adding an address already present. cmd || true lets the script continue, but it also hides every other failure of that command. An option that expresses the expected case is safer (see Idempotent Scripts Check the Current State Before Changing It).

References