Robust Scripts
Strict Mode
Safer Defaults
Strict shell options turn common scripting mistakes into early failures. Defaults keep missing inputs explicit without weakening the script.
Program
Play the script to watch a missing argument become a default value, then become a filename-safe slug.
strict_mode.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
set -euo pipefail
input="${1:-draft report}"
safe="${input// /_}"
echo "$safe"
options ← errexit, nounset, pipefail
3set -euo pipefail4input="${1:-draft report}"values this steperrexit, nounset, pipefailoptionsinput ← draft report
3set -euo pipefail4input="${1:-draft report}"5safe="${input// /_}"values this stepdraft reportinputunset$1safe ← draft_report
4input="${1:-draft report}"5safe="${input// /_}"6echo "$safe"values this stepdraft_reportsafedraft reportinputecho "$safe"
5safe="${input// /_}"6echo "$safe"outputdraft_reportvalues this stepdraft_reportsafe
Follow the Script
set -euo pipefailturns onerrexit,nounset, andpipefail.$1is unset in the traced run.${1:-draft report}makesinputequaldraft report.${input// /_}changes spaces to underscores.- The script prints
draft_report. | step | value | | --- | --- | | options |errexit,nounset,pipefail| |$1| unset | |input|draft report| |safe|draft_report| | stdout |draft_report|
strict mode
`set -euo pipefail` makes failed commands, unset variables, and failed pipelines visible.
default expansion
`${1:-draft report}` supplies a value when the first argument is missing or empty.
substitution
`${input// /_}` replaces every space in the value.
Exercise: strict_mode.sh
Reproduce draft_report, then trace how the unset first argument becomes the safe output.