Interview Prep/Shell Scripting/Best practices and rapid-fire commands

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Best practices and rapid-fire commands