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".
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner