Interview Prep/Shell Scripting/Scenarios: backups, log rotation and housekeeping

Write the core of a Postgres backup that streams `pg_dump` through gzip to S3 and never uploads an empty dump.

IntermediateScenarioScenarios: backups, log rotation and housekeeping
Answer

Situation read → In pg_dump | gzip, a failed pg_dump still produces a small valid gzip file, and without pipefail the job reports success.

What I'd do →

set -Eeuo pipefail
out="/var/backups/pg/app-$(date -u +%Y%m%dT%H%M%SZ).sql.gz"
tmp=$(mktemp "${out}.XXXXXX"); trap 'rm -f -- "$tmp"' EXIT
pg_dump --format=plain --no-owner -h "$PGHOST" -U backup app | gzip -6 > "$tmp"
gzip -t "$tmp"
(( $(stat -c %s "$tmp") > 1024 )) || { echo "dump suspiciously small" >&2; exit 1; }
mv -- "$tmp" "$out"
aws s3 cp --only-show-errors --sse aws:kms "$out" "s3://$BUCKET/pg/"
  1. pipefail makes the pipeline fail if pg_dump fails.
  2. Credentials come from ~/.pgpass (mode 0600) or PGPASSWORD from a secret, not argv.
  3. For large databases use --format=custom (compressed, parallel restore with pg_restore -j).

Why → Empty backups are the most common way teams discover they had no backup.

Interview tip → Mention a size sanity check, and a scheduled test restore, as two separate guards.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: backups, log rotation and housekeeping