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 →
- Build the new config in a temp file in the same directory:
tmp=$(mktemp /etc/nginx/.nginx.conf.XXXXXX). - Trap cleanup:
trap 'rm -f -- "$tmp"' EXIT. - Validate the candidate before installing it:
nginx -t -c "$tmp"(or copy into place in a staging include and runnginx -t). - Keep a backup, then swap atomically:
cp -a nginx.conf nginx.conf.bak && mv -f -- "$tmp" nginx.conf. - 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.
More on Scenarios: writing and hardening scripts
You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?IntermediateA script with `#!/bin/sh` works on CentOS but fails on Ubuntu with `Syntax error: "(" unexpected`. What is going on and what do you do?BeginnerYou need a deploy script that humans and CI both call with `--env`, `--version` and `--dry-run`. How do you design its interface?BeginnerA maintenance script must run as the `deploy` user, never as root, because files it creates must be owned by `deploy`. How do you enforce that?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA script is run both by engineers and by cron. Cron logs are full of colour codes and the script sometimes hangs waiting for input. Fix it.Beginner