Interview Prep/Shell Scripting/Troubleshooting: strict mode, exit codes, pipelines and traps

You added `trap 'echo "failed at line $LINENO" >&2' ERR`, but when a command inside a function fails, nothing is printed and the script just exits.

IntermediateTroubleshootingTroubleshooting: strict mode, exit codes, pipelines and traps
Answer

Likely causes → The ERR trap is not inherited by functions, command substitutions or subshells unless set -E (errtrace) is on. set -e still exits, so you get the exit without the message.

Diagnose →

bash -c 'set -e; trap "echo ERR \$LINENO" ERR; f(){ false; }; f'    # prints nothing
bash -c 'set -Ee; trap "echo ERR \$LINENO" ERR; f(){ false; }; f'   # prints ERR 1

Fix → Use the full strict header and a trap function that reports useful context:

set -Eeuo pipefail
on_err() { echo "ERROR: '${BASH_COMMAND}' exited $1 at ${BASH_SOURCE[1]}:${BASH_LINENO[0]}" >&2; }
trap 'on_err $?' ERR

Prevent → Make set -Eeuo pipefail the template header. Note that without set -e, the trap fires once for the failing command and again for the function call that returns non-zero, so keep the trap idempotent or log only.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: strict mode, exit codes, pipelines and traps