Lesson 7.1: Robust shell scripts: fail safely
Admin scripts run as root, unattended, often from cron, and bash's defaults are forgiving: an unset variable becomes an empty string, a failed command is ignored, a failing step in a pipeline is hidden. Together they turn small mistakes into deleted data. A few habits make scripts fail safely: set -euo pipefail, ${VAR:?} for required settings, quoting, cd -- with a check, trap to clean up, and flock so two copies never run at once. In the lab you find a cleanup script that would delete files in the wrong directory, prove it with a trace, and replace it with a safe version.
17 min
You will learn to
- Explain bash's unsafe defaults
- Trace a script with bash -x
- Use set -euo pipefail and ${VAR:?}
- Clean up with trap
- Prevent overlapping runs with flock
Key terms
- set -e / -u / -o pipefail
- Stop on errors / treat unset variables as errors / fail a pipeline if any part fails.
- ${VAR:?message}
- Expands VAR, or stops the script with the message if it's unset or empty.
- trap
- Runs a command when the script exits or receives a signal.
- flock
- Runs a command while holding a lock file; -n gives up if someone else holds it.
- bash -x / bash -n
- Trace every command after expansion / check syntax without running.
← Changing passwords · All lessons · Shared-library hijacking →