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

A wrapper logs `stages: 0` for a failed `pg_dump | gzip > db.gz`. The code reads `${PIPESTATUS[@]}` on the line after an `if`.

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

Likely causes → PIPESTATUS is overwritten by every command, including [[ ]], echo, and the if test itself. By the time it is read, it describes the last simple command, not the pipeline.

Diagnose →

false | true; [[ 1 == 1 ]]; echo "${PIPESTATUS[@]}"   # 0, the [[ ]] result

Fix → Copy it immediately after the pipeline, in the same statement position:

pg_dump -Fc "$DB" | gzip -c > "$tmp"
st=("${PIPESTATUS[@]}")
(( st[0] == 0 )) || die "pg_dump failed (${st[0]})"
(( st[1] == 0 )) || die "gzip failed (${st[1]})"

Prevent → With pipefail you usually only need the pipeline's overall status; copy PIPESTATUS when you need to report which stage failed.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

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