← All articles
· 2 min read

Bash strict mode and the traps that save you

set -euo pipefail is table stakes, but it has sharp edges. The traps, the pitfalls with pipes, and the one-line error trap I never ship without.

The first line of every script I ship is the same, and it has prevented more quiet disasters than any amount of careful coding:

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

Four letters, four promises. -e exits on the first failed command instead of ploughing on. -u treats an unset variable as an error, so a typo in $BACKUP_DIR fails loudly rather than deleting /. -o pipefail makes a pipeline fail if any stage fails, not just the last — without it, cmd | grep x reports success even when cmd crashed. -E makes ERR traps fire inside functions.

Add a trap that tells you where it died, and debugging stops being archaeology:

trap 'echo "error on line $LINENO: $BASH_COMMAND" >&2' ERR

Now the sharp edges, because strict mode has them. Under -u, expanding a possibly-empty array or an optional variable aborts, so give it a default:

name="${1:-default}"        # ok even if $1 is unset
files=("${LIST[@]:-}")      # ok even if LIST is empty

And under -e, a command that legitimately may "fail" (a grep that finds nothing, say) will kill the script unless you handle it. Append || true when you genuinely do not care, or test explicitly:

if ! grep -q "pattern" file; then
    echo "not found, continuing"
fi

Strict mode does not make Bash safe — nothing does — but it converts a whole class of silent, destructive bugs into a stack trace at the line that caused them. That trade is never wrong.