Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

How do you get the exit status of every command in a pipeline?

AdvancedConceptFunctions, exit codes, strict mode and traps
Answer
pg_dump app | gzip > app.sql.gz
st=("${PIPESTATUS[@]}")         # copy immediately; the next command overwrites it
if (( st[0] != 0 )); then echo "pg_dump failed (${st[0]})" >&2; exit 1; fi
if (( st[1] != 0 )); then echo "gzip failed (${st[1]})" >&2; exit 1; fi

Without this (or pipefail), a failed pg_dump produces a valid but empty .gz, and your backup job reports success. This is a top cause of "we had backups but they were empty".

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps