Skip to content

Bash set -euo pipefail: what each flag does and where it bites

Make a Bash script stop on the first failure with set -euo pipefail, understand what -e does not catch, and add a trap that says where it stopped.

Checked 2026-11-19

By default Bash carries on after a command fails. A backup script whose copy failed will still print "Backup OK". These three options at the top of a script change that:

#!/usr/bin/env bash
set -euo pipefail

-e: stop when a command fails

Any command that exits with a non-zero status ends the script.

Where it does not apply: a failing command that is part of a test. Commands in if, while, until, on the left of && or ||, and after ! do not stop the script, because their failure is being checked. This is deliberate:

if grep -q error app.log; then echo "found"; fi   # grep failing is fine here
mkdir -p "$dir" || exit 1                          # handled by hand

The trap inside functions: -e is switched off for the whole body of a function that is called as a test, such as if myfunc; then. Keep the check explicit in functions you call that way.

-u: an unset variable is an error

rm -rf "$BUILD_DIR/"    # with BUILD_DIR unset, without -u this is rm -rf "/"

With -u, Bash stops with BUILD_DIR: unbound variable. For a variable that may legitimately be empty, give a default: "${1:-}" or "${PORT:-8080}".

-o pipefail: a pipe fails if any part fails

curl -s https://example.com/data | gzip > data.gz

Without pipefail, the pipe's status is gzip's, which succeeds on empty input, so a failed download looks fine. With it, the pipe fails if any command in it does.

Watch for head: producer | head -1 can make producer fail with SIGPIPE when head closes the pipe early, which then fails the pipe.

Say where it stopped

trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR

Checklist for a script others will run

  • set -euo pipefail at the top.
  • Quote every variable: "$file", never $file.
  • exit with a non-zero code on your own errors, and print them to stderr (>&2).
  • Run shellcheck script.sh; it finds most of the rest.
Practise it on a real machineBash That Fails Loudly lab
Open the lab