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

You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → Half-deploys mean a step fails and the script keeps going. Before rewriting anything, make failures visible and stop on them.

What I'd do →

  1. Put it in Git if it is not already, and run shellcheck -x deploy.sh to get a list of real bugs (unquoted variables, unchecked cd, masked return codes).
  2. Add a strict header and an error trap so the next failure tells us where:
    set -Eeuo pipefail
    trap 'echo "FAILED line $LINENO: $BASH_COMMAND (exit $?)" >&2' ERR
    
  3. Run it against staging with bash -x and a PS4 that prints line numbers, fixing everything strict mode trips on (often optional variables needing ${VAR:-}).
  4. Restructure so the switch-over is a single atomic step at the end (build in a new release directory, then ln -sfn and reload), so a failure before that point changes nothing live.
  5. Add a lock (flock -n) so two people cannot deploy at once.

Why → Most "sometimes" bugs are unchecked failures plus non-atomic changes. Strict mode surfaces them, atomic switching makes them harmless.

Interview tip → Say you would not big-bang rewrite it; you make it observable first, then refactor in small, tested steps.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts