Why each section matters
set -euo pipefail
-e exits on any error. -u treats unset vars as errors. -o pipefail catches pipe failures. Together they stop silent failures that corrupt prod.
trap on EXIT/ERR
Catches unexpected exits and signals. Runs cleanup code, closes connections, and logs the line that failed. You'll know exactly what broke and where.
Dry-Run Mode
Run with --dry-run to preview all actions without executing them. Essential for destructive operations and onboarding teammates.
Lock File
Prevents two instances running simultaneously — critical for cron jobs. Uses /tmp/script.lock and cleans up on exit.
ENV Validation
Fails fast at startup if required environment variables are missing. Saves you from half-executed deployments caused by missing secrets.
Rollback Hook
Define a rollback() function that fires on any failure. Keeps your system in a clean state and avoids manual recovery work.