Interview Prep/Shell Scripting/Scenarios: writing and hardening scripts

A script edits `/etc/nginx/nginx.conf` and reloads nginx. If someone hits Ctrl+C mid-way, nginx is left with a broken config. How do you make it safe?

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → In-place edits are not atomic, and an interrupted edit leaves a half-written file that fails on the next reload or reboot.

What I'd do →

  1. Build the new config in a temp file in the same directory: tmp=$(mktemp /etc/nginx/.nginx.conf.XXXXXX).
  2. Trap cleanup: trap 'rm -f -- "$tmp"' EXIT.
  3. Validate the candidate before installing it: nginx -t -c "$tmp" (or copy into place in a staging include and run nginx -t).
  4. Keep a backup, then swap atomically: cp -a nginx.conf nginx.conf.bak && mv -f -- "$tmp" nginx.conf.
  5. Reload, and on failure restore the backup and reload again.

Why → mv on the same filesystem is atomic; an interruption at any point leaves either the old or the new config, never half of one.

Interview tip → Mention that SIGKILL cannot be trapped, which is exactly why the atomic rename matters more than the trap.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts