You are asked to add `set -e` to a large legacy script that has run in production for years. What are the risks?
IntermediateScenarioScenarios: writing and hardening scripts
Answer
Situation read → The script may rely on commands failing harmlessly: grep returning 1 when nothing matches, diff returning 1 when files differ, ((count++)) at zero, test as the last line of a function.
What I'd do →
- Grep for commands with meaningful non-zero codes:
grep,diff,cmp,test/[,((,readat EOF,pgrep,systemctl is-active. - Make intended "failures" explicit:
grep -q x f || true,if grep -q ...; then,count=$((count + 1)). - Run it in staging with
set -Eeuo pipefailand anERRtrap that logs the line, and fix each trip. - Roll out behind a flag at first (
STRICT=1) if the script is critical.
Why → set -e changes behaviour for every command; blindly adding it can turn a working script into one that stops halfway, which may be worse.
Interview tip → Saying "set -e is a safety net, not error handling" signals maturity.
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