Defensive Bash: Strict Mode, Validation, and Cleanup
MediumShell Scripting20-30 minA script that runs on autopilot has to fail loudly and clean up after itself. Write /root/scripts/deploy.sh, a defensive wrapper around a config in /root/case/configs/<name>.conf. It takes one argument, a config name, and must:
1. Enable strict mode: set -euo pipefail.
2. Validate input — with no argument, print usage: deploy.sh <name> to stderr and exit 2; with a name whose /root/case/configs/<name>.conf doesn't exist, print error: unknown config <name> to stderr and exit 3.
3. On success (the config exists), create a lock file /root/run/deploy.lock, register a trap to remove it on EXIT, print deployed <name> to stdout, and exit 0 — the lock must not survive the run.
Grading runs your script three ways (no arg, unknown name, the assigned valid name) and checks the exit codes, the messages, and that the trap cleaned up the lock. See /root/case/brief.txt for a skeleton.
- Enable strict mode (set -euo pipefail)
- Reject missing input with a usage message on stderr and exit 2
- Reject an unknown config with an error on stderr and exit 3
- On success, lock, print, and clean up via a trap on EXIT (exit 0)
Hands-on lab: you work on a real Linux box in your browser, graded on the machine's actual state.
