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

An `ERR` trap runs `send_alert`, but when the alert itself fails (Slack is down), the script loops, printing the same error repeatedly until it is killed.

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

Likely causes → Commands run inside the trap handler can trigger the trap again when they fail (with set -E and functions involved, the handler's own failing curl re-enters it). A handler that retries or re-raises can recurse.

Diagnose → bash -x shows on_err being entered from within on_err. trap -p ERR confirms what is registered.

Fix → Disable the trap at the start of the handler and make the alert best-effort:

on_err() {
  local rc=$? cmd=$BASH_COMMAND line=${BASH_LINENO[0]}
  trap - ERR
  set +e
  log ERROR "'$cmd' failed ($rc) at line $line"
  send_alert CRITICAL "backup failed at line $line" || log WARN "alert delivery failed"
  exit "$rc"
}
trap on_err ERR

Prevent → Trap handlers must never fail: no strict mode inside, short timeouts on network calls (curl --max-time 5), and an explicit exit with the original status.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

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