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

The backup failed and printed errors, but cron and the monitoring wrapper both recorded exit code 0. The last line of the script is `main "$@" 2>&1 | tee -a "$LOG"`.

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

Likely causes → A pipeline's status is the status of its last command, tee, which succeeded. pipefail was not set (or was set inside main, which runs in the pipeline's subshell and does not affect the outer shell).

Diagnose →

bash -c 'f(){ return 3; }; f | tee /dev/null; echo "rc=$? stages=${PIPESTATUS[*]}"'   # rc=0 stages=3 0

Fix → Redirect the whole script's output once, near the top, instead of piping main:

set -Eeuo pipefail
exec > >(tee -a "$LOG") 2>&1      # or simply: exec >>"$LOG" 2>&1 under systemd/cron
main "$@"

Alternatively set pipefail in the outer shell or exit "${PIPESTATUS[0]}" after the pipeline.

Prevent → Test the failure path: a bats test that forces aws to fail and asserts status -ne 0.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

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