Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps