How do you write an ERR trap that reports the failing line and command?
IntermediateConceptFunctions, exit codes, strict mode and traps
Answer
set -Eeuo pipefail
on_err() {
local rc=$1 line=$2 cmd=$3
echo "ERROR: line $line: '$cmd' exited with $rc" >&2
}
trap 'on_err $? $LINENO "$BASH_COMMAND"' ERR
Capture $? as the first thing in the trap string, before any other command overwrites it. -E makes the trap fire inside functions too. For a stack trace, loop over FUNCNAME, BASH_SOURCE and BASH_LINENO in on_err.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner