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

The error log says `ERROR: curl failed with exit code 0`, which is useless. The code is `if ! curl -fsS "$URL" -o "$out"; then log ERROR "curl failed with exit code $?"; fi`.

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

Likely causes → $? inside the then branch holds the status of the whole condition, ! curl ..., which is 0 (the negation succeeded). The original curl status is gone.

Diagnose →

bash -c 'if ! false; then echo "rc=$?"; fi'     # rc=0

Fix → Capture the status without negation:

if curl -fsS --max-time 10 "$URL" -o "$out"; then
  :
else
  rc=$?
  log ERROR "curl failed with exit code $rc"     # 6 DNS, 7 connect, 22 HTTP >= 400, 28 timeout
fi
# or: curl ... || { rc=$?; log ERROR "curl failed ($rc)"; return "$rc"; }

Prevent → Save $? into a variable on the very next statement, before any [[ ]], echo or ! touches it.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

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