My ERR trap stayed silent until I added one letter to set -euo pipefail

My ERR trap stayed silent until I added one letter to set -euo pipefail

●2 ●38 ●102
calendar_today • schedule1 min read

A nine-line script, set -euo pipefail on line 2 and an ERR trap on line 3 whose only job is to print the failing command and its line number. A helper function then runs mkdir /proc/export, a directory that cannot be created. On bash 5.3.9 it printed mkdir's own complaint and exited 1. The trap said nothing: no command, no line, the two facts it was registered to report.

By default the ERR trap is not inherited by functions, command substitutions or subshells. Errexit killed the script from inside the function; the trap, registered at the top level, never saw the failure. One letter fixes it:

set -Eeuo pipefail
trap 'echo "✗ failed: ${BASH_COMMAND} (line ${LINENO})" >&2' ERR

-E (errtrace) makes the trap follow the script into functions. Same run, same mkdir error, now followed by ✗ failed: mkdir /proc/export (line 5).

Two more silent spots from the same session. local out=$(false) inside a function carried on to the next line and the script exited 0, because local succeeded and its status is the one bash checks. Declare on one line, assign on the next. And in an EXIT handler, capture $? on the first line: moved below an rm -f, it reports rm's zero, and a script ending in exit 3 exits 0.

Where errexit goes silent, nounset defaults and the assembled skeleton with both traps are in the strict-mode bash script template, checked against bash 5.3.


I bundled the scripts I copy onto every new server, plus 10 bonus ones, into the Production Bash Toolkit. 30-day refund if it isn't useful.

Want more #devops & #linux deep dives?

Join 6,093+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

A deploy guard that passes with no token

BashSnippets - Nov 24

A Textile Mill's Dyehouse Ramp Curve: Get One Step Wrong and the Sheet Belongs to the Master

aiomniu - Oct 18

set -euo pipefail — the Line That Would Have Saved Me from Deleting the Wrong Directory

BashSnippets - Jun 3

A For Loop Skipped Every File With a Space and Called the Backup a Success

BashSnippets - Jun 18

I killed the process I started. The port stayed taken.

BashSnippets - Nov 5
chevron_left
3.8k Points • 142 Badges
North America • bashsnippets.xyz
79Posts
38Comments
14Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!