How do you make a script support a dry-run mode cleanly?
BeginnerConceptBest practices and rapid-fire commands
Answer
Wrap every state-changing command in a function that prints instead of executing when dry-run is on:
DRY_RUN=${DRY_RUN:-0}
run() {
if (( DRY_RUN )); then
printf 'DRY RUN:'; printf ' %q' "$@"; printf '\n'
else
"$@"
fi
}
run rm -rf -- "/srv/app/releases/$old"
run systemctl reload nginx
printf %q shows exactly how the arguments would be passed, including spaces. Read-only commands (queries, find) still run so the dry run shows real targets.
More on Best practices and rapid-fire commands
What does a production-ready script template look like?AdvancedWhat logging practices do you follow in automation scripts?IntermediateRapid fire: one-liners for disk, memory and process checks.BeginnerRapid fire: one-liners for logs and text.BeginnerRapid fire: one-liners for files and housekeeping.BeginnerRapid fire: one-liners for JSON, YAML and cloud CLIs.Beginner