Visual: one line
cp $f "$dst", with echo output beside it that looks normal, but the command fails.Narration: echo tells you the values you think you have; set -x tells you the arguments Bash actually runs.
set -x + custom PS4 (${BASH_SOURCE}:${LINENO}:${FUNCNAME}) to read execution traces, use BASH_XTRACEFD to write traces to a separate file, use caller to print the call stack, use bash -n and trap … DEBUG for syntax checking and step-by-step observation..shellcheckrc to make justified suppressions.main functions,:: package separators, declaring local variables separately from their assignment, etc.).run,assert_success,assert_output,setup/teardown, a separate temporary directory for each test, and PATH injecting test doubles (stubs).time / hyperfine to measure the gains./bin/sh), the Bash 3.2 that ships with macOS, and BusyBox ash, and use checkbashisms and shellcheck -s sh to check portability.test/*.bats test suite, Makefile/justfile (lint / fmt / test), GitHub Actions pipeline (ShellCheck with a pinned version + shfmt -d + bats),VERSION files and release tarball.| # | Time | Module | Core content | Animation / interaction | Lab (~/bashlab) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: testing and CI toolchain | Install ShellCheck, shfmt, bats-core and helper libraries, checkbashisms and hyperfine; get the opsctl starting code | Environment self-check | check-tools.sh |
| 1 | 00–06 | Debugging: set -x, PS4, BASH_XTRACEFD and caller | xtrace principles, PS4 expansion and level prefixes, trace redirection, caller call stack, bash -n, trap DEBUG/ERR | xtrace step-through player (live PS4 expansion, call stack) | Add OPSCTL_TRACE=1 switch |
| 2 | 06–13 | Static checking: ShellCheck rules and suppression | Common SC codes, severity levels, directives,.shellcheckrc, optional checks, output formats | Core animation: ShellCheck finds and fixes issues one by one | Fix deploy-old.sh of 10 warnings |
| 3 | 13–21 | Formatting and style: shfmt and style guide | shfmt options and EditorConfig,-d/-l/-w, Google Shell Style Guide key rules | shfmt options live preview | Configure for opsctl .editorconfig and format |
| 4 | 21–28 | Testing: bats-core, assertions and test doubles | bats execution model, run, bats-assert, setup/teardown, temporary directories, PATH doubles | Core animation: one bats run (setup → run → assert → teardown) | Write 21 tests for opsctl (and uncover a real problem) |
| 5 | 28–35 | Performance: avoiding subshells, builtins first and profiling | fork/exec cost, command substitution, parameter expansion,printf -v,time/TIMEFORMAT, hyperfine,EPOCHREALTIME timing | fork counter: three ways to write the same task | Log-processing function sped up 50× |
| 6 | 35–42 | Portability: POSIX sh, dash, Bash 3.2 and BusyBox | bashism checklist, dash, macOS Bash 3.2, BusyBox ash, checkbashisms, version guards | Portability matrix: feature × shell | Running scripts on bash:3.2 / busybox in containers |
| 7 | 42–50 | When not to use Bash: signals for migrating to Python / Go | Complexity signals, data structures, error handling, concurrency, cross-platform; migration strategy | “Should we switch languages?” scorer | New codes subcommand: awk and Python dual implementations, cross-checked with the same test suite |
| 8 | 50–60 | opsctl v1.0: testing, CI and release | Test suite, Makefile/justfile, GitHub Actions, VERSION, tarball and checksums | CI pipeline simulator + interactive troubleshooting tree | Release opsctl-1.0.0.tar.gz |
| — | After class | Cheat sheet · Capstone lab | Take over a “legacy script”: add tests, fix warnings, make it portable, connect CI | Final quiz (12 questions) | Capstone lab |
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Execution tracing and call stacks | ✓ | · | · | ✓ | ✓ | · | · | ✓ | set -x,PS4,BASH_XTRACEFD,caller | M1 |
| Static analysis and suppression strategy | · | ✓ | ✓ | · | · | ✓ | · | ✓ | shellcheck -x -S,.shellcheckrc | M2, M8 |
| Formatting and style conventions | · | ✓ | ✓ | · | · | · | · | ✓ | shfmt -d,.editorconfig | M3, M8 |
| Automated testing and doubles | · | · | · | ✓ | · | ✓ | ✓ | ✓ | bats,run,assert_output | M4, M8 |
| Performance profiling and optimization | ✓ | · | · | · | ✓ | · | ✓ | · | time,hyperfine,strace -c -f | M5 |
| Portability (POSIX / old versions / BusyBox) | · | ✓ | ✓ | · | · | ✓ | ✓ | ✓ | checkbashisms,shellcheck -s sh,dash -n | M6 |
| Technology choice (when to switch languages) | · | · | ✓ | · | ✓ | ✓ | ✓ | · | — | M7 |
| CI and release | · | ✓ | ✓ | ✓ | · | · | · | ✓ | make check,git archive,sha256sum | M8, capstone lab |
| Topic | Why it is not in this lesson | Where to learn |
|---|---|---|
| Full GitHub Actions syntax (matrix, caching, environments, OIDC, reusable workflows) | This lesson only builds one minimal working check pipeline | GitHub 8 hours |
| Running the same checks in GitLab CI / Jenkins | the same idea: call make check | GitLab 8 hours,Jenkins 8 hours |
| Configuration convergence and idempotent deployment across multiple hosts | Beyond the scope of “scripts”; hand over to configuration management tools (see M7) | Ansible 8 hours |
| Principles of strict mode, trap, locks and retries | Covered in Lesson 4; used directly in this lesson | Hour 4 |
| Python / Go language itself | M7 covers only “when and how to migrate” | Official tutorials for each language |
| Bash interview questions and production issue collection | Collected in Hour 8 | Hour 8 |
~/bashlab folder.bash 5.3-2ubuntu1; upstream patches are up to 5.3.20). Tool versions: ShellCheck 0.11.0 (2025-08-03, same as Ubuntu 26.04 apt), shfmt 3.14.1 (2026-09-06; Ubuntu 26.04 apt has 3.12.0), bats-core 1.14.0 (2026-07-21; Ubuntu 26.04 apt has 1.13.0), bats-assert 2.2.4, bats-support 0.3.0, hyperfine 2.0.0 (apt has 1.19.0), dash 0.5.12 (the default /bin/sh on Ubuntu 26.04 and Debian 13 /bin/sh), BusyBox 1.37.0. Output marked “actual run results (Bash 5.2 / dash, Git for Windows)” was really run on this machine; all other output (especially ShellCheck, shfmt and bats output) is marked “example”: the format comes from upstream docs and source code, so check details against your actual output.~/bashlab, and have run ~/bashlab/make-data.sh to generate ~/bashlab/data/ (servers.csv,access.log etc.). Optional environments: a Linux course linuxlab VM, WSL2, macOS + Homebrew bash, or a container docker run --rm -it -v "$PWD":/work -w /work bash:5.3.bin/opsctl,lib/log.sh (log::info/warn/error writes stderr),lib/util.sh (util::die,util::require_cmd),lib/cmd_*.sh (one file per subcommand, function cmd::<name>),etc/opsctl.conf,test/. Exit code convention: 0 success, 1 general error, 2 usage error, 3 missing dependency.sudo apt update sudo apt install -y shellcheck shfmt bats bats-support bats-assert devscripts hyperfine busybox # devscripts is large; if you only need checkbashisms, you can install just that: # sudo apt install -y --no-install-recommends devscripts
Ubuntu 26.04 (resolute) repository versions: shellcheck 0.11.0, shfmt 3.12.0, bats 1.13.0, bats-assert 2.2.4, bats-support 0.3.0, devscripts 2.26.7 (provides /usr/bin/checkbashisms), hyperfine 1.19.0, busybox 1.37.0. The bats helper libraries installed by apt are located in /usr/lib/bats/bats-assert/ and /usr/lib/bats/bats-support/, and tests can load them with bats_load_library (M4).
brew install bash shellcheck shfmt bats-core hyperfine /opt/homebrew/bin/bash --version | head -1 # Intel Macs: /usr/local/bin/bash /bin/bash --version | head -1 # the system one is still 3.2.57; do not delete it
bats-support / bats-assert are used in this lesson via git submodules in the project (see step 3), so macOS, Linux and CI load them the same way, without relying on system packages.
cd ~/bashlab/opsctl docker run --rm -v "$PWD":/mnt -w /mnt koalaman/shellcheck:v0.11.0 -x bin/opsctl lib/*.sh docker run --rm -v "$PWD":/mnt -w /mnt mvdan/shfmt:v3.14.1 -d bin/opsctl lib test docker run --rm -v "$PWD":/code bats/bats:1.14.0 test docker run --rm -v "$PWD":/w -w /w bash:3.2 bash bin/opsctl help # for the portability experiment (M6)
lib/*.sh the wildcards are expanded by the host shell before being passed into the container as arguments. The paths are all relative, so they work the same inside the container. Image tags koalaman/shellcheck:v0.11.0,mvdan/shfmt:v3.14.1,bats/bats:1.14.0,bash:3.2,bash:5.3,busybox:1.37 were all verified to exist on Docker Hub on 2026-11-17.This lesson does not rewrite opsctl; instead it adds tests, quality gates and a release process to the code written in Lessons 3–6. If you don't have the previous lessons' results, the starting code comes, in order, from:Lesson 3 capstone lab(v0.1: entry point,log,util,config,servers,config subcommands,etc/opsctl.conf) → Lesson 4 Module 8(v0.2: new bin/opsctl and lib/log.sh, appended to lib/util.sh v0.2 functions,cmd_export.sh,cmd_doctor.sh,test/flaky.sh) → Lesson 5 Module 8(lib/cmd_logs.sh,lib/logs_report.awk, configuration keys logs_top/logs_format) → Lesson 6 Module 8(v0.3: version number, 8 new configuration keys,cmd_health.sh,cmd_backup.sh,cmd_deploy.sh). The code of these four lessons was extracted from the courseware piece by piece, v0.3.0 was rebuilt in order, and each row of the table below was verified by actually running it on Bash 5.2 on this machine:
| Interface | Behavior (measured on this machine) | Exit code |
|---|---|---|
bin/opsctl → opsctl::main | The version guard requires Bash ≥ 4.4; after that, set -Eeuo pipefail + inherit_errexit + util::setup_traps; global options -c/--config,-v,-h,-V; source by name lib/cmd_<name>.sh and call cmd::<name>; help is generated automatically from # opsctl-summary: (all 8 subcommands are covered) | Unknown subcommand → 2; with no arguments, prints usage to stderr and returns 2 |
lib/log.sh (v0.2) | log::debug/info/warn/error Writes to stderr, format time LEVEL opsctl[PID]: message; colors are used when stderr is a terminal and NO_COLOR is not set; OPSCTL_LOG_FILE also saves a copy | — |
lib/util.sh | EX_OK/EX_ERR/EX_USAGE/EX_DEP,util::die <msg> [code=1],util::usage_error (→ 2),util::require_cmd (→ 3),util::csv_split,util::retry <count> <initial seconds> <command…> (exponential backoff + full jitter; 2/126/127 are not retried),util::lock,util::mktemp_dir,util::cleanup_add | 1 / 2 / 3 |
lib/config.sh | Priority: command line > environment variable OPSCTL_<KEY> > etc/opsctl.conf > default value; when the command line overrides a different environment variable value, one DEBUG line is printed only under -v (the debug setting); keys include env,data_dir,output,logs_*,health_*,backup_*,deploy_* | — |
opsctl servers list [-e ENV] [-o table|tsv] | read <data_dir>/servers.csv (used in tests to point OPSCTL_DATA_DIR at the fixture directory); table has a header row, tsv has none | invalid env → 2; file unreadable → 1 |
opsctl logs report [--top N] [--format text|tsv] [FILE|-] | single awk scan (lib/logs_report.awk); tsv first line metric key value | no valid lines / file unreadable → 1; invalid option value → 2 |
opsctl health [-t SEC] [-r N] [-e CODE] URL | health::probe Uses curl -sS -o /dev/null -w '%{http_code} %{time_total}' --connect-timeout T --max-time 2T -- URL, provided by util::retry N 1 retries; logs health ok: … code=200 / health fail: … code=000 curl_rc=7 / giving up after N attempts; also reads OPSCTL_HEALTH_RETRIES etc. | healthy → 0; retries exhausted → 1; missing URL, non-http(s), unknown option → 2; missing curl → 3 |
The only entry-point change in v1.0: the version number is now provided by VERSION file (the M8 release process uses it as the single source of truth). Lesson 6 changed the entry point's readonly OPSCTL_VERSION="0.2.0" to "0.3.0"; the sed below replaces that line with a file read (works with or without readonly style):
cd ~/bashlab/opsctl echo 0.3.0 > VERSION sed -i -E 's/^(readonly +)?OPSCTL_VERSION=.*/OPSCTL_VERSION=$(<"$OPSCTL_HOME\/VERSION") || exit 1\nreadonly OPSCTL_VERSION/' bin/opsctl grep -n 'OPSCTL_VERSION' bin/opsctl | head -3 bin/opsctl -V # Test fixture: a separate small data directory (including fields with quoted commas) mkdir -p test/fixtures/data cat > test/fixtures/data/servers.csv <<'EOF' name,env,region,ip,role web-dev-1,dev,canadacentral,10.0.1.10,web web-stg-1,staging,canadacentral,10.0.2.10,web web-prod-1,prod,canadacentral,10.0.3.10,web db-prod-1,prod,ca-central-1,10.0.3.20,"db,primary" EOF
30:OPSCTL_VERSION=$(<"$OPSCTL_HOME/VERSION") || exit 1 31:readonly OPSCTL_VERSION 59:$OPSCTL_PROG $OPSCTL_VERSION - ops toolbox for ~/bashlab opsctl 0.3.0
Note: macOS's BSD sed does not support \n in the replacement string; edit those two lines by hand in an editor. $(<file) occurs after set -Eeuo pipefail , and when the file is missing || exit 1 it returns a clear exit code. The fixture deliberately does not use ~/bashlab/data: tests must depend only on files in the repository for the results to be stable. Lesson 5 Module 8 already generated test/fixtures/access.sample.log and report.expected.tsv (used by M4's logs.bats ); you can also generate it in setup_file with the Lesson 1 ~/bashlab/make-data.sh "$BATS_FILE_TMPDIR/data" command to produce the full dataset (deterministic: 12 servers, 6 of them prod).
cd ~/bashlab/opsctl git init -q 2>/dev/null || true git submodule add https://github.com/bats-core/bats-core.git test/bats git submodule add https://github.com/bats-core/bats-support.git test/test_helper/bats-support git submodule add https://github.com/bats-core/bats-assert.git test/test_helper/bats-assert # Pin to the verified versions (reproducible) git -C test/bats checkout -q v1.14.0 git -C test/test_helper/bats-support checkout -q v0.3.0 git -C test/test_helper/bats-assert checkout -q v2.2.4 test/bats/bin/bats --version
Bats 1.14.0
This is the directory layout recommended by the official bats-core tutorial (test/bats + test/test_helper/…). When others clone the repository, they need to git clone --recurse-submodules, or run after cloning git submodule update --init.
cat > ~/bashlab/check-tools.sh <<'EOF'
#!/usr/bin/env bash
# Print the versions of the tools this lesson needs; missing ones are marked MISSING
for t in bash shellcheck shfmt bats checkbashisms hyperfine dash busybox; do
if command -v "$t" >/dev/null 2>&1; then
case $t in
bash) v=$BASH_VERSION ;;
shellcheck) v=$(shellcheck --version | awk '/^version:/{print $2}') ;;
shfmt) v=$(shfmt --version) ;;
bats) v=$(bats --version) ;;
checkbashisms) v=$(checkbashisms --version 2>&1 | head -n1) ;;
hyperfine) v=$(hyperfine --version) ;;
busybox) v=$(busybox 2>&1 | head -n1) ;;
*) v=present ;;
esac
printf '%-14s %s\n' "$t" "$v"
else
printf '%-14s MISSING\n' "$t"
fi
done
EOF
chmod +x ~/bashlab/check-tools.sh && ~/bashlab/check-tools.sh
bash 5.3.0(1)-release shellcheck 0.11.0 shfmt v3.12.0 bats Bats 1.13.0 checkbashisms This is checkbashisms, from the Debian devscripts package, version 2.26.7 hyperfine hyperfine 1.19.0 dash present busybox BusyBox v1.37.0 (Ubuntu 1:1.37.0-7ubuntu1) multi-call binary.
$ bin/opsctl -V opsctl 1.0.0 $ OPSCTL_DATA_DIR=test/fixtures/data bin/opsctl servers list --env prod -o tsv web-prod-1 prod canadacentral 10.0.3.10 web db-prod-1 prod ca-central-1 10.0.3.20 db,primary $ bin/opsctl nope; echo "rc=$?" 2026-11-17T09:46:56-0500 ERROR opsctl[446]: unknown command: nope Try 'opsctl --help' for more information. rc=2 $ dash bin/opsctl -V; echo "rc=$?" opsctl: please run with bash, not sh rc=3
rm -rf,make clean) only act on ~/bashlab the directory inside; the M2 negative example deploy-old.sh is only for ShellCheck analysis; do not run it.+,++,+++ prefixes each mean.${BASH_SOURCE},${LINENO},${FUNCNAME} and explain why it must be assigned in single quotes.BASH_XTRACEFD to separate the trace from normal stderr, use caller / FUNCNAME / BASH_LINENO to print the call stack.bash -n for syntax checking, trap … ERR to report the failure location, and trap … DEBUG for step-through observation.set -x (equivalent to set -o xtrace) makes Bash before executing each simple command, for command, case command, select command or arithmetic for command, print the expanded command and its arguments to stderr, prefixed with PS4 's expanded value (default "+ "). The key is “after expansion”: what you see is the real argv, after parameter expansion, command substitution, arithmetic expansion, word splitting and pathname expansion are all complete, which is exactly what echo debugging often fails to show.
PS4's first character is repeated according to the “indirection level”: commands in the main shell show +, command substitution $( ) commands show ++, and two levels of nesting show +++. So seeing ++ tells you the command ran in a subshell.
| Tool | Purpose | When to use |
|---|---|---|
set -x / bash -x script | Prints each command after expansion | “Why is this variable empty?” “Why was this argument split into two?” |
set -v | Prints the raw source lines as read (unexpanded) | Compare with -x to see the difference before and after expansion |
PS4 | xtrace line prefix, expanded before every print | Adds file, line, function and timestamp |
BASH_XTRACEFD (Bash ≥ 4.1) | Sends xtrace to a specified file descriptor | Too much trace output, and you don't want to pollute stderr or logs |
caller [n],FUNCNAME,BASH_SOURCE,BASH_LINENO | Call stack information | Prints “who called me” in die / ERR traps |
bash -n script | Parse only, don't execute (noexec) | Syntax check before committing and before deploying |
trap '…' DEBUG | Each simple command execution before runs | Step-by-step observation, simple profiling, logging $BASH_COMMAND |
trap '…' ERR + set -E | Runs when a command returns non-zero (and is not in a conditional context) | Reports the failing command and location |
echo debugging means editing code, is easy to miss, and shows what you think the values are. xtrace shows what Bash actually passes to the command, for example rm -rf $dir/* when dir is empty, xtrace clearly shows + rm -rf /bin /boot …— something no echo can easily expose for you. Combined with the file and line numbers from PS4, you can jump straight to the failure point even in large scripts.
export PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
${LINENO} it is expanded at assignment time into a fixed number, so every line afterward shows the same line number.${BASH_SOURCE[0]##*/} Drop the directory and keep only the file name; a source library file that is sourced shows the library's file name.${FUNCNAME[0]:-main}: top-level code is not inside a function, so FUNCNAME is empty and the default value main is used as a placeholder.${EPOCHREALTIME} (Bash ≥ 5.0) to get microsecond timestamps for rough profiling (M5).export After that, bash -x started subscripts also inherit this PS4; however, Bash started as root does not inherit PS4 from the environment (for security reasons), so set it inside root scripts.bash -n, or shfmt -d (M3, stricter parsing).set -x … set +x to avoid thousands of lines of noise.OPSCTL_TRACE=1) + BASH_XTRACEFD to write to a file for later analysis.util::die or an ERR trap, print the call stack.| echo / printf | set -x + PS4 | trap DEBUG | bashdb (external debugger) | |
|---|---|---|---|---|
| Requires code changes | Yes, adding | a line or an environment variable | one line | No |
| Sees expanded arguments | Only sees what you print | Yes | Via $BASH_COMMAND (before expansion) | Yes |
| Breakpoints / stepping | No | No | Can be simulated | Yes |
| Usable in CI / production | Yes | Yes (watch for secret leaks) | Use with care (high overhead) | Rarely used |
echo "prod: 2" shows it as echo 'prod: 2'. ② “bash -n passes, so there are no syntax problems”—it only parses and does not run,eval so strings inside source , files being sourced, and content inside command substitutions are only parsed at runtime (command substitution content is parsed early in Bash 5.2+, but sourced files are not). ③ “set -x is safe”—it prints passwords and tokens verbatim into the log, so in production and CI you must first set +x handle secrets. ④ “$BASH_COMMAND shows the expanded command”—in fact it is the raw source text, with variables not yet expanded.caller i the output is the line number, function name and file of the “i-th level caller” (line numbers come from an actual run of Lab 1 using the Lesson 3 code with the trace switch added; your line numbers will differ)On the left is a 9-line script. Choose a PS4 scheme and a trace destination, then click “Next”: each step highlights the line being executed and shows the xtrace line it produces (expanded live according to the chosen PS4; commands inside command substitution show two +) signs; on the right, the current call stack (FUNCNAME / BASH_LINENO) and the three output streams are shown. The trace matches an actual run on Bash 5.2 on this machine (timestamps are examples).
| Command / variable | Purpose | Notes |
|---|---|---|
bash -x script.sh args | Enable xtrace for the whole script | no script changes needed; bash -xv also print the raw lines |
set -x … set +x | Trace only a section | { set +x; } 2>/dev/null the set +x itself is not printed |
PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: ' | Trace prefix | Single quotes! The first character is repeated per nesting level |
exec {fd}>trace.log; BASH_XTRACEFD=$fd | Write trace to a file | Bash ≥ 4.1; unset it or set it to an empty string to go back to stderr |
caller / caller N | Current caller / N-th level caller | No arguments: line file; with N: line function file; out of range returns non-zero |
bash -n script.sh | Syntax check | Exit code 0 means the syntax is valid; can be looped over multiple files |
trap 'cmd' DEBUG | Runs before each simple command | not inherited inside functions by default; needs set -T (functrace) |
trap 'cmd' ERR | Runs when a command fails | functions and subshells need set -E (errtrace) |
$BASH_COMMAND | Text of the command currently executing (or just failed) | Most useful in DEBUG/ERR traps |
declare -p var | Print variables precisely (including type and arrays) | More reliable than echo; shows the difference between empty and unset |
mkdir -p ~/bashlab/m7 && cd ~/bashlab/m7
cat > dbg.sh <<'EOF'
#!/usr/bin/env bash
export PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
greet() {
local name=$1
printf 'hello %s\n' "$name"
}
set -x
n=2
greet "$n"
set +x
EOF
bash dbg.sh
+ dbg.sh:8:main: n=2 + dbg.sh:9:main: greet 2 + dbg.sh:4:greet: local name=2 + dbg.sh:5:greet: printf 'hello %s\n' 2 hello 2 + dbg.sh:10:main: set +x
bash -c 'PS4="+ "; set -x; a=$(echo $(echo hi)); echo "$a"'
+++ echo hi ++ echo hi + a=hi + echo hi hi
cat > xfd.sh <<'EOF'
exec 5>trace.log
BASH_XTRACEFD=5
PS4='+ ${LINENO}: '
set -x
x=$((1+2))
echo "x=$x"
set +x
EOF
bash xfd.sh; echo "--- trace.log:"; cat trace.log
x=3 --- trace.log: + 5: x=3 + 6: echo x=3 + 7: set +x
Note: The manual states that setting BASH_XTRACEFD to 2 and then unsetting it will close standard error. Do not write BASH_XTRACEFD=2; to restore, just run unset BASH_XTRACEFD (only if it points to an fd you opened yourself).
cat > err.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
on_err() {
local rc=$? i
printf 'ERROR rc=%d at %s:%d: %s\n' "$rc" "${BASH_SOURCE[1]}" "${BASH_LINENO[0]}" "$BASH_COMMAND" >&2
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
printf ' at %s (%s:%d)\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]}" "${BASH_LINENO[i-1]}" >&2
done
}
trap on_err ERR
load_conf() { grep -q '^env=' /nonexistent/opsctl.conf; }
start() { load_conf; }
start "$@"
EOF
bash err.sh; echo "rc=$?"
grep: /nonexistent/opsctl.conf: No such file or directory ERROR rc=2 at err.sh:11: grep -q '^env=' /nonexistent/opsctl.conf at load_conf (err.sh:11) at start (err.sh:12) at main (err.sh:13) rc=2
The bottom-most level main is not a function you wrote, but the name Bash gives the top level of the script Without set -E , the ERR trap does not fire inside functions, and you only see start returning failure, losing the line where the real error occurred.
cat > caller.sh <<'EOF'
die() { local frame=0; while caller $frame; do ((frame++)); done; }
inner() { die; }
outer() { inner; }
outer
EOF
bash caller.sh
printf 'if true; then\n echo hi\n' > bad.sh
bash -n bad.sh; echo "rc=$?"
2 inner caller.sh 3 outer caller.sh 4 main caller.sh bad.sh: line 3: syntax error: unexpected end of file rc=2
Bash 5.3 improved this kind of error message, adding which compound command was left unclosed (for example, pointing to the one from line 1 if); the exact wording depends on your version.
bash -c 'trap '\''echo "DEBUG> $BASH_COMMAND"'\'' DEBUG; a=1; echo $a'
DEBUG> a=1 DEBUG> echo $a 1
OPSCTL_TRACE switch to the entry point: in bin/opsctl 's readonly OPSCTL_PROG after (before the libraries load), insert:
cd ~/bashlab/opsctl
python3 - <<'PY'
import pathlib
p = pathlib.Path("bin/opsctl"); s = p.read_text(encoding="utf-8")
add = '''
# Trace switch: OPSCTL_TRACE=1 writes to stderr; OPSCTL_TRACE=/path/file writes to a file
if [[ -n ${OPSCTL_TRACE:-} ]]; then
export PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
if [[ ${OPSCTL_TRACE} != 1 ]]; then
exec {OPSCTL_TRACE_FD}>>"${OPSCTL_TRACE}"
BASH_XTRACEFD=${OPSCTL_TRACE_FD}
fi
set -x
fi
'''
anchor = "readonly OPSCTL_PROG\n"
if "OPSCTL_TRACE" not in s:
s = s.replace(anchor, anchor + add, 1)
p.write_text(s, encoding="utf-8")
PY
grep -n 'OPSCTL_TRACE' bin/opsctl | head -3
35:# Trace switch: OPSCTL_TRACE=1 writes to stderr; OPSCTL_TRACE=/path/file writes to a file
36:if [[ -n ${OPSCTL_TRACE:-} ]]; then
38: if [[ ${OPSCTL_TRACE} != 1 ]]; then
You can also paste the middle section by hand in an editor. Python is used here only so the step can be copied and run as-is, without depending on GNU/BSD sed differences. Note that exec {OPSCTL_TRACE_FD}>>file lets Bash automatically allocate a free fd ≥ 10.
OPSCTL_TRACE=1 OPSCTL_DATA_DIR=test/fixtures/data bin/opsctl servers list --env prod -o tsv 2>&1 \ | grep -n 'servers::list\|cmd::servers' | head -4
162:+ 1794926908.252304 opsctl:96:opsctl::load_command: declare -F cmd::servers 163:+ 1794926908.252407 opsctl:136:opsctl::main: log::debug 'dispatch: cmd::servers list --env prod -o tsv' 164:+ 1794926908.252436 log.sh:30:log::debug: log::_emit debug 'dispatch: cmd::servers list --env prod -o tsv' 170:+ 1794926908.252619 opsctl:137:opsctl::main: cmd::servers list --env prod -o tsv
Before line 162 is library loading,util::setup_traps and config::init traces — which is why you filter by file/function. log::debug At info level nothing is printed, but its calls still appear in the trace.
OPSCTL_TRACE=/tmp/opsctl.trace OPSCTL_DATA_DIR=test/fixtures/data bin/opsctl servers list --env prod -o tsv wc -l < /tmp/opsctl.trace
web-prod-1 prod canadacentral 10.0.3.10 web db-prod-1 prod ca-central-1 10.0.3.20 db,primary 1456
A call that outputs only two lines produced over a thousand lines of trace (most of it from util::csv_split 's character-by-character loop) — a foreshadowing of the performance discussion in M5.
util::die print the call stack: change lib/util.sh in util::die to (the signature stays the same: util::die <msg> [code=1]):
util::die() { # util::die <message> [exit_code=1]
local i
log::error "$1"
if [[ -n ${OPSCTL_DEBUG:-} ]]; then
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
printf ' at %s (%s:%d)\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]##*/}" "${BASH_LINENO[i - 1]}" >&2
done
fi
exit "${2:-1}"
}
OPSCTL_DEBUG=1 OPSCTL_DATA_DIR=/nope bin/opsctl servers list; echo "rc=$?"
2026-11-17T09:48:28-0500 ERROR opsctl[399]: cannot read /nope/servers.csv (run ~/bashlab/make-data.sh first?)
at servers::list (cmd_servers.sh:63)
at cmd::servers (cmd_servers.sh:24)
at opsctl::main (opsctl:137)
at main (opsctl:140)
rc=1
The last level main is the script's top level (line 140 opsctl::main "$@"), not a function you wrote. Since v0.2 the entry point has util::setup_traps, but util::die is explicit exit, so it does not trigger ERR reporting.
for f in bin/opsctl lib/*.sh; do bash -n "$f" || echo "syntax error: $f"; done; echo done
Problem: The deployment script failed once every 20 runs in CI and could not be reproduced locally. Approach: Set OPSCTL_TRACE=$RUNNER_TEMP/trace.log in CI, and upload the trace as an artifact on failure; the trace showed that one curl returned 000, immediately followed by jq parsing empty input. Fix: Add retries to the API call (Lesson 6) and check the HTTP status code. Limitation: The trace may contain tokens; before uploading, use sed to redact them, or turn tracing off around sections that handle secrets set +x.
Problem: Someone added set -x to a production script for debugging and forgot to remove it; the database password went into the centralized log system along with mysql -p"$PASS" 's trace. Approach: Rotate the password and clean up the logs; change the policy to “enable tracing only through an environment variable switch”, and have ShellCheck and code review catch hard-coded set -x. Better approach: pass passwords through a file or stdin (--defaults-extra-file,--password-stdin), so they are not visible even when tracing is on.
Problem: A library that 30 scripts source lib/util.sh reported “argument is empty”, and the log only had the library's line number. Approach: After die prints the FUNCNAME/BASH_SOURCE/BASH_LINENO call stack, the caller is identified the first time it happens. Result: Errors from all later scripts include stack information, and average time to locate a problem dropped from “hours” to “minutes”.
Cause: PS4 is assigned with double quotes,${LINENO} so ${LINENO} is expanded to a fixed value at assignment time.
PS4="+ ${LINENO}: " # Wrong: expanded at assignment time
PS4='+ ${LINENO}: ' # Right: expanded each time a trace is printedCause:if/fi,do/done,case/esac,{/} or quotes or heredoc terminators are unpaired. The reported line number is usually the end of the file, not the actual location of the missing piece.
bash -n script.sh shfmt -d script.sh # the error location is usually more accurate (M3) grep -nE '^\s*(if|fi|for|while|until|do|done|case|esac)\b' script.sh # rough pairing check
Another common cause: Windows line endings (CRLF) make the heredoc terminator become EOF\r so it no longer matches; check with file script.sh ,sed -i 's/\r$//' script.sh and fix it (or in .gitattributes set *.sh text eol=lf).
Cause: The script uses CRLF line endings, so each line has an extra \r, which xtrace shows as $'\r'.
bash -x script.sh 2>&1 | grep -m3 $'\r' sed -i 's/\r$//' script.sh
Cause: Set BASH_XTRACEFD=2 and then unset BASH_XTRACEFD—Bash closes that fd, which means it closed stderr.
Fix: Point BASH_XTRACEFD only at an fd you opened yourself with exec {fd}>file fd; to restore, unset it (this closes your own fd).
Cause: By default, the ERR trap is not inherited by shell functions, command substitutions or subshells.
set -E # equivalent to set -o errtrace trap 'on_err' ERR
Similarly, DEBUG and RETURN traps need set -T (functrace) to take effect inside functions. Also, a failure inside if,while conditions,&&/|| or on the left side of an && / || list does not trigger ERR (the same exception as set -e; see Lesson 4).
deploy , and do not print set +x this line itself.deploy() {
set -x
# ... code to trace ...
{ set +x; } 2>/dev/null
}PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO} ${FUNCNAME[0]:-main} ${EPOCHREALTIME}: '
# EPOCHREALTIME needs Bash ≥ 5.0; the unit is seconds (the fractional part is microseconds)① Temporarily change the crontab entry to OPSCTL_TRACE=/tmp/backup.trace /path/backup.sh (or bash -x), and set PS4 to a version that includes file and line; ② after the next run, find in the trace rm that line and check the expanded arguments: cron has very few environment variables (PATH only has /usr/bin:/bin, without the variables you set in .bashrc), so a variable is most likely empty, causing rm -rf "$DIR"/* to become rm -rf /var/backups/* and the like; ③ fix: guard variables with ${DIR:?} against empty values, explicitly set PATH and the required variables in the script; ④ use ShellCheck (SC2115) to catch this pattern at commit time (M2).
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
cp $f "$dst", with echo output beside it that looks normal, but the command fails.disable,source,source-path,shell,enable), and use .shellcheckrc to standardize project configuration.-S,-f,-x and -o to integrate ShellCheck into the editor, Makefile and CI.set -e exception rules from Lesson 4. Importance:★★★★★ShellCheck is a static analyzer written in Haskell: it parses the script into a syntax tree (AST), then runs hundreds of rules on the tree to find syntax errors, semantic traps (quotes, exit codes, scope), portability problems (bashisms used in #!/bin/sh scripts) and style issues. It does not execute the script, so it can safely analyze rm -rf and similar dangerous code. Each rule has a number:
| Number range | Meaning | Examples |
|---|---|---|
| SC1xxx | Parser issues: syntax, quoting, encoding | SC1091 cannot follow a sourced file; SC1017 the file contains CR (Windows line endings) |
| SC2xxx | General semantic issues (the most) | SC2086 unquoted; SC2155 declaration and assignment combined |
| SC3xxx | Non-portable features in a sh (POSIX) dialect | SC3010 [[ ]]; SC3043 local; SC3030 arrays |
| Level | Meaning | Typical |
|---|---|---|
| error | Almost certainly a bug or syntax error | SC2045 iterating over ls output, SC1073 parse failure |
| warning | Likely to cause wrong behavior | SC2164 unhandled cd failure, SC2155, SC2046, SC2115, SC2034 |
| info | Causes problems for some inputs | SC2086 unquoted, SC1091 |
| style | Better style | SC2006 backticks, SC2181 checking $? |
-S warning means only report warning and above (error + warning). Many teams start their CI gate from -S warning , then gradually tighten to the default style level.
| Code | Problem code | What happens | Fix |
|---|---|---|---|
| SC2086 | cp $f /backup | f="my file.txt" is split into two arguments; f="*" the value is glob-expanded | cp -- "$f" /backup |
| SC2046 | chmod 644 $(find . -name '*.conf') | the command substitution result is split on whitespace and glob-expanded | find … -exec chmod 644 {} + or mapfile -d '' |
| SC2155 | local v=$(cmd) / export V=$(cmd) | the exit code is that of local/export (always 0), so cmd's failure is swallowed,set -e and set -e does not trigger | First local v, then v=$(cmd) |
| SC2164 | cd $dir | after cd fails, the script keeps running in the current directory and runs the following rm | cd -- "$dir" || exit |
| SC2181 | cmd; if [ $? -ne 0 ] | inserting any command in between (such as logging) overwrites $?; and under set -e, a cmd failure never reaches the if | if ! cmd; then |
| SC2034 | unused=1 | a misspelled variable (VERISON) or dead code | delete it, fix the spelling, or export |
| SC2045 | for f in $(ls *.log) | fails when file names contain spaces or newlines | for f in ./*.log |
| SC2115 | rm -rf $dir/* | When dir is empty, it becomes rm -rf /* | rm -rf -- "${dir:?}"/* |
| SC2006 | `cmd` | nesting and escaping are hard to read | $(cmd) |
| SC1091 | source lib/x.sh | ShellCheck does not follow (analyze) sourced files | -x + # shellcheck source=… |
.shellcheckrc (searched upward from the file's directory; the user's home directory config is also read); the content is the same directives with the # shellcheck prefix removed.enable= ; shellcheck --list-optional lists all of them. Since 0.11.0, SC2002 (useless cat) is an optional check that is off by default.Editor (the VS Code ShellCheck extension, Vim ALE, Neovim LSP via bash-language-server) → before commit (pre-commit hook) → CI gate (M8). The earlier you find it, the cheaper it is.
| ShellCheck | bash -n | shfmt | checkbashisms | |
|---|---|---|---|---|
| Finds syntax errors | Yes | Yes | Yes (stricter) | Partially |
| Finds semantic traps (quoting, exit codes) | Yes | No | No | No |
| Portability | Yes (SC3xxx) | No | Dialect-aware parsing | Yes (specialized) |
| Rewrites code | Partially auto-fixable (-f diff) | No | Formatting | No |
# shellcheck disable=all is the easiest way”—global suppression also removes protection from new code; suppress one by one and state the reason. ④ “-x is just an optional item”—without -x (or external-sources=true), variables and functions defined in sourced libraries are invisible to ShellCheck, producing many SC2154 false positives.The sample is a “legacy” deployment script deploy-old.sh (for analysis only; do not run it). Click “Next”: ShellCheck reports each issue in turn (tty format, with a caret ^ pointing at the location); click “Fix” to change that line to the correct form; the right side records the remaining warning count. Use the -S button above to switch the minimum severity level and observe which warnings are filtered. Warning text matches the ShellCheck 0.11.0 wiki; the output layout is an example.
shellcheck deploy-old.sh.| Command | Purpose | Notes |
|---|---|---|
shellcheck script.sh | Check (default tty format) | Exit code 0 = no issues, 1 = issues found |
shellcheck -x bin/opsctl lib/*.sh | Follow sourced files | equivalent to external-sources=true |
-S error|warning|info|style | Minimum severity level | Common in CI gates -S warning Starting point |
-e SC2086,SC2034 / -i SC2086 | Exclude / include only certain codes | Command-line level, broader than directives; use with care |
-s sh|bash|dash|ksh|busybox | Specify dialect | For library files without a shebang, use # shellcheck shell=bash is better |
-f tty|gcc|json1|checkstyle|diff|quiet | Output format | gcc good for editor navigation; checkstyle good for CI reports; diff auto-fixable |
-o all / --list-optional | Enable / list optional checks | e.g. require-variable-braces,check-extra-masked-returns |
-P SCRIPTDIR | source search path | equivalent directive source-path= |
--norc | ignore .shellcheckrc | Investigate “why local and CI results differ” |
shellcheck -W 0 --wiki-link-count=0 | do not print wiki links | Compact output |
mkdir -p ~/bashlab/m7 && cd ~/bashlab/m7 cat > deploy-old.sh <<'EOF' #!/bin/bash src=$1 dest=/srv/releases/`date +%s` unused_count=0 cd $dest for f in $(ls $src/*.tar.gz); do cp $f . done tar xzf app.tar.gz if [ $? -ne 0 ]; then echo "extract failed"; exit 1; fi export VERSION=$(cat $src/VERSION) chmod 644 $(find . -name '*.conf') rm -rf $dest/old/* EOF shellcheck -f gcc deploy-old.sh
deploy-old.sh:3:6: note: Use $(...) notation instead of legacy backticks `...`. [SC2006]
deploy-old.sh:4:1: warning: unused_count appears unused. Verify use (or export if used externally). [SC2034]
deploy-old.sh:5:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
deploy-old.sh:5:4: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:6:10: error: Iterating over ls output is fragile. Use globs. [SC2045]
deploy-old.sh:6:16: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:7:6: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:10:6: note: Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?. [SC2181]
deploy-old.sh:11:8: warning: Declare and assign separately to avoid masking return values. [SC2155]
deploy-old.sh:11:23: note: Double quote to prevent globbing and word splitting. [SC2086]
deploy-old.sh:12:11: warning: Quote this to prevent word splitting. [SC2046]
deploy-old.sh:13:8: warning: Use "${var:?}" to ensure this never expands to /* . [SC2115]
deploy-old.sh:13:8: note: Double quote to prevent globbing and word splitting. [SC2086]
The gcc format shows both info and style as note; the tty format shows SC2086 (info),SC2006 (style) such precise levels. Column numbers depend on your actual output.
cat > deploy-fixed.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
src=${1:?usage: deploy-fixed.sh SRC_DIR}
dest=/srv/releases/$(date +%s)
mkdir -p -- "${dest}"
cd -- "${dest}" || exit 1
for f in "${src}"/*.tar.gz; do
[[ -e ${f} ]] || continue # keep the wildcard as-is when nothing matches
cp -- "${f}" .
done
if ! tar xzf app.tar.gz; then
echo "extract failed" >&2
exit 1
fi
VERSION=$(<"${src}/VERSION")
export VERSION
find . -name '*.conf' -exec chmod 644 {} +
rm -rf -- "${dest:?}/old/"*
EOF
shellcheck deploy-fixed.sh && echo "ShellCheck: clean"
ShellCheck: clean
shellcheck -S warning deploy-old.sh | grep -c '^In ' # count error+warning only shellcheck -f diff deploy-old.sh > fix.patch # only includes the auto-fixable suggestions git apply --check fix.patch 2>/dev/null || patch -p1 --dry-run < fix.patch shellcheck -f json1 deploy-old.sh | jq -r '.comments[] | "\(.line):\(.code) \(.level)"' | head
-f diff It only covers some rules (such as adding quotes); structural issues like SC2045 and SC2155 still need manual fixes.
# Suppress a single command, and state the reason
# shellcheck disable=SC2086 # RSYNC_OPTS is intentionally a list of options split on spaces
rsync ${RSYNC_OPTS} -- "$src" "$dst"
# Tell ShellCheck the real file for a dynamic source
# shellcheck source=lib/log.sh
source "${OPSCTL_HOME}/lib/log.sh"
# Library file without a shebang: declare the dialect on the first line
# shellcheck shell=bash
cat > ~/bashlab/opsctl/.shellcheckrc <<'EOF' # ShellCheck configuration for the opsctl project (searched upward from the checked file's directory) external-sources=true source-path=SCRIPTDIR # Optional checks (off by default): don't use which (use command -v) enable=deprecate-which # Turn on stricter checks one at a time, e.g. enable=add-default-case (case must have a *) branch) EOF cd ~/bashlab/opsctl && shellcheck bin/opsctl lib/*.sh && echo "opsctl: clean"
cd ~/bashlab/m7 shellcheck -f json1 deploy-old.sh | jq -r '.comments[] | "\(.level) SC\(.code)"' | sort | uniq -c | sort -rn
5 info SC2086
1 warning SC2164
1 warning SC2155
1 warning SC2115
1 warning SC2046
1 warning SC2034
1 style SC2181
1 style SC2006
1 error SC2045
If jq is not available, use shellcheck -f gcc deploy-old.sh | grep -o 'SC[0-9]*' | sort | uniq -c.
shellcheck -S warning deploy-old.sh to confirm the count has dropped.bash -c 'set -e; f() { local v=$(false); echo "still running, v=[$v]"; }; f'
bash -c 'set -e; f() { local v; v=$(false); echo "not reached"; }; f; echo "rc=$?"'
still running, v=[]
Line one: local exit code is 0,false failures are swallowed and the script keeps running. Line two: the exit status of an assignment is that of the command substitution,set -e takes effect, so the function and the whole bash -c exit immediately (so rc= is never printed either).
mkdir -p ~/bashlab/m7/q && cd ~/bashlab/m7/q touch 'my file.txt' f='my file.txt' ls $f; echo "---"; ls "$f"
ls: cannot access 'my': No such file or directory ls: cannot access 'file.txt': No such file or directory --- 'my file.txt'
.shellcheckrc, then:
cd ~/bashlab/opsctl shellcheck bin/opsctl lib/*.sh; echo "rc=$?"
Entry points from Lesson 3 onward already carry # shellcheck source-path=SCRIPTDIR/.. and # shellcheck source=lib/log.sh directives; the v0.3 libraries and subcommands contain no disable directives (cleanup is handled by util::cleanup_add registration, not expanding variables inside a trap string, so SC2064 does not need to be suppressed) — this is the direction this module recommends: rewrite first, suppress last. If your Lesson 3–6 implementation has warnings, fix them one by one using the table in this module; for code you really must keep, use a single-line directive with a reason.
Problem: A cleanup script rm -rf $STEAMROOT/* deleted all of a user's files when the variable was empty — a real incident in Steam for Linux in 2015 (valve-software/steam-for-linux issue #3671). Approach: ShellCheck's SC2115 is designed exactly for this pattern; fix it to rm -rf -- "${STEAMROOT:?}"/*, and at the top of the script, set -u. Lesson: Any script containing dangerous commands must go through the ShellCheck gate.
Problem: A repository with 200 scripts ran ShellCheck for the first time and got more than 3,000 warnings, which could not be fixed all at once. Approach:① CI first uses -S error, and after the errors are fixed, switches to -S warning; ② for files that were changed, use the default level (git diff --name-only origin/main -- '*.sh' | xargs -r shellcheck); ③ clean up a batch of SC2086 every week. Result: Two months later the whole repository reached zero warnings at the default level.
Problem: A developer used # shellcheck disable=SC2086 to bypass a genuinely problematic unquoted variable. Approach: The team requires every disable directive to include # reason, and uses grep -rn 'shellcheck disable' --include='*.sh' | grep -v '#.*#' in CI to find directives without a reason so that reviewers can focus on them.
Cause: by default, sourced files are not followed.
shellcheck -x bin/opsctl # or write external-sources=true in .shellcheckrc # When the path is dynamic, add this above the source line: # shellcheck source=lib/log.sh
Note:source= relative paths in it are resolved against ShellCheck's current working directory, so run it from the repository root, or use source-path=SCRIPTDIR (relative to the script's own directory).
Cause: the variable is assigned in a sourced file, passed in from the environment, or misspelled.
Fix: add -x so ShellCheck can see the library; for environment variables use ${VAR:?} or ${VAR:-default} to express intent; if it is truly injected externally, use : "${VAR:?VAR must be set}" declared at the top of the script.
Cause: library files have no shebang, so ShellCheck does not know which dialect to use.
sed -i '1i # shellcheck shell=bash' lib/foo.sh # GNU sed; or manually add it on the first line
Cause: the file uses Windows line endings (CRLF).
tr -d '\r' < script.sh > script.tmp && mv script.tmp script.sh printf '*.sh text eol=lf\n*.bats text eol=lf\nbin/* text eol=lf\n' >> .gitattributes
Cause: different versions (for example local 0.9, while CI 0.11 added SC2327–SC2335); or a ~/.shellcheckrc in the local user's home directory suppresses some rules.
shellcheck --version | head -2 shellcheck --norc bin/opsctl lib/*.sh # exclude the effect of personal config
Fix: CI and local use the same pinned version (M8 downloads v0.11.0 in CI), and project configuration only goes in the repository's .shellcheckrc.
git diff --name-only --diff-filter=d origin/main -- '*.sh' | xargs -r shellcheck -x -S warning
local out=$(cd $dir; ls)local out
out=$(cd -- "$dir" && ls) || return
# Better approach: don't parse ls; use an array instead: files=("$dir"/*).shellcheckrc in disable=SC2086, reasoning that “our variables contain no spaces.” How would you respond?I disagree with global suppression. ① “No spaces” is today's assumption; file names, user input and cloud resource names may contain spaces or glob characters tomorrow (*,?,[); ② SC2086 also prevents pathname expansion, and when the variable's value is * the consequences are severe; ③ where splitting is really needed (such as option lists), use an array "${opts[@]}", and for the few places that cannot be changed, use a single-line directive with a reason. An acceptable compromise: CI first uses -S warning (SC2086 is info and won't block), while drawing up a plan to fix it gradually.
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
shfmt -d (check),-l (list),-w (rewrite) to format scripts, and understand the effects of -i,-ci,-bn,-sr,-fn, and -s ..editorconfig to save the shfmt configuration, and know that “once formatting arguments are given on the command line, EditorConfig is completely ignored”..sh library files being parsed as POSIX.shfmt is a command-line tool from the project by Daniel Martí (mvdan), written in Go, that acts as a shell parser / formatter / interpreter mvdan.cc/sh . It fully parses the script into a syntax tree and then prints it back according to uniform rules, so it is both a formatter, and also a stricter bash -n than syntax checker (it statically parses all syntax and requires valid UTF-8). Supported dialects: bash,posix,mksh,bats,zsh (from 3.14).
| Option | EditorConfig key | Effect |
|---|---|---|
-i N | indent_style / indent_size | 0 = Tab (default), N > 0 = N spaces |
-ci | switch_case_indent (new spelling case_indent) | case branches are indented one level more than the case keyword |
-bn | binary_next_line | when wrapping lines, move &&,||,| to the start of the next line |
-sr | space_redirects | add a space after redirection operators: > file |
-fn | function_next_line | function's { goes on the next line |
-kp | keep_padding | keep spaces used for alignment |
-s | simplify | simplify code (for example remove the redundant $(( $a )) in $) |
-ln bash|posix|mksh|bats|zsh | shell_variant (new spelling language_dialect) | specify the dialect; default auto |
Old and new spellings: the 3.14 manual says the old key names shell_variant,switch_case_indent are still accepted; to remain compatible with the 3.12.0 in Ubuntu 26.04 apt, this lesson's .editorconfig uses the old spellings.
shfmt -d In CI it serves as a “format gate” and a “strict syntax check”.When -ln auto (the default): first check the file extension (such as .bash,.mksh,.bats); otherwise check the shebang; if neither exists, treat as bash. But the manual specifically notes: .sh an extension is a special case, meaning posix, and only a valid shebang can override it. opsctl's lib/*.sh has no shebang, so it is parsed as POSIX, and when it meets [[ ]],local bash syntax beyond those produces an error — the fix is to, in .editorconfig , for *.sh specify shell_variant = bash.
| Rule | Key points from the original | How it applies in opsctl |
|---|---|---|
| When to use Shell | Scripts over 100 lines, or with unintuitive control flow, should move to a structured language as soon as possible | M7 migration signals |
| Use Bash only | “Bash is the only shell scripting language permitted for executables.” | #!/usr/bin/env bash |
| Indentation and line width | 2 spaces, no tabs; 80 columns maximum | indent_size = 2 |
| Pipeline line breaks | Keep on one line if it fits; otherwise one stage per line, with the pipe at the start of the line and 2-space indentation | binary_next_line = true |
| Function naming | lowercase with underscores; library functions may use :: as a package separator | log::info,util::die,cmd::servers |
| main function | scripts containing at least one other function must have a main, and the last line main "$@" | bin/opsctl |
| Local variables | declare with local; when the value comes from a command substitution, declaration and assignment must be separate | corresponds to SC2155 |
| Testing | [[ … ]] prefer [ … ] over test | consistent within the library [[ ]] (the version guard at the entry point is an exception; see M6) |
| Command substitution | use $(command), not backticks | corresponds to SC2006 |
| Error output | all error messages are written to STDERR | lib/log.sh all >&2 |
| File extensions | executables use .sh or no extension; libraries must use .sh and must not be executable | bin/opsctl no extension,lib/*.sh permissions 644 |
| Constants | all uppercase,readonly or declare -r | readonly OPSCTL_HOME |
| Tools | recommended: use ShellCheck on all scripts | M2, M8 |
| Other | avoid eval; use arrays to hold argument lists; read command output with process substitution or readarray rather than piping into while | Lessons 2, 3 |
The Google style guide itself does not mention shfmt; mapping its indentation and pipeline rules to shfmt options is this lesson's approach (-i 2 -bn -ci is the example combination from the shfmt manual and is closest to the Google style).
-s and also makes only equivalent simplifications), and does not add quotes to variables; semantic problems still rely on ShellCheck. ② “I wrote shfmt -i 2 -d, and the dialect settings in EditorConfig will also apply”—no: as soon as any parse or print argument is given on the command line, EditorConfig is ignored entirely. ③ “Formatted code must be checked line by line by hand”—shfmt works on the complete syntax tree, and formatting preserves semantics; but the first repository-wide formatting should be a separate commit to make review and git blame --ignore-rev easier.On the left is a messily formatted input; on the right is shfmt's output. Switch options to see which lines each option affects (affected lines are highlighted). The output is simulated from shfmt's printing rules to help you understand the options; for the actual output, shfmt check your own machine's real output.
| Command | Purpose | Notes |
|---|---|---|
shfmt file.sh | Print the formatted result to stdout | does not modify files |
shfmt -d . | Print a diff and exit non-zero if the formatting differs | CI gate; NO_COLOR=1 turn off color |
shfmt -l . | List files whose formatting differs (also exits non-zero) | and -w combined: shfmt -l -w . |
shfmt -w file… | Rewrite in place | commit first, then rewrite, for easy rollback |
shfmt -f . | List only the Shell files in a directory | identified by extension and shebang; new in 3.14 --detect exec|all |
shfmt -i 2 -ci -bn | manual's example combination | close to Google style |
shfmt -ln bash / -p | force dialect / POSIX | makes EditorConfig ineffective |
shfmt --filename=x.sh < x.sh | make EditorConfig apply when reading from stdin | for editor integration |
cd ~/bashlab/m7
cat > messy.sh <<'EOF'
#!/usr/bin/env bash
backup(){
local src=$1 dst=$2
if [ -d "$src" ] &&
[ -w "$dst" ];then
tar -czf "$dst/b.tgz" -C "$src" . >"$dst/b.log"
fi
case $3 in
full) echo full;;
*) echo incr;;
esac
}
EOF
shfmt messy.sh | cat -A | head -n 6 # cat -A shows tabs as ^I
shfmt -i 2 -ci -bn messy.sh
#!/usr/bin/env bash
backup() {
local src=$1 dst=$2
if [ -d "$src" ] \
&& [ -w "$dst" ]; then
tar -czf "$dst/b.tgz" -C "$src" . >"$dst/b.log"
fi
case $3 in
full) echo full ;;
*) echo incr ;;
esac
}
cat > ~/bashlab/opsctl/.editorconfig <<'EOF'
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
# Shell: 2 spaces, case branch indentation, binary operators at line start (close to Google style)
[*.sh]
indent_style = space
indent_size = 2
# Key: .sh is parsed as posix by default, and library files have no shebang
# (EditorConfig only supports whole-line comments; don't write end-of-line comments)
shell_variant = bash
switch_case_indent = true
binary_next_line = true
[bin/opsctl]
indent_style = space
indent_size = 2
switch_case_indent = true
binary_next_line = true
[*.bats]
indent_style = space
indent_size = 2
shell_variant = bats
switch_case_indent = true
binary_next_line = true
[{Makefile,*.mk}]
indent_style = tab
EOF
cd ~/bashlab/opsctl
shfmt -d bin/opsctl lib test/*.bats 2>/dev/null; echo "shfmt rc=$?"
shfmt -l -w bin/opsctl lib # rewrite where there are differences (commit once first!)
Note: when shfmt reads EditorConfig,must not be given any formatting arguments, so the Makefile only contains shfmt -d bin/opsctl lib test. Lesson 3's code has many “alignment spaces” and single-line case case branches (such as -v|--verbose) config::set_flag …; shift ;;), and in Lesson 3's cmd_servers.sh code, util::in_list … \ a line starting with || after a line break is kept under binary_next_line = true , while a || at the end of a line is moved to the start of the next line — the first time, a large diff shfmt -d appears is normal; after reviewing, run -w once and commit it separately.
printf 'if true; then\n echo hi\n' > bad.sh shfmt bad.sh >/dev/null; echo "rc=$?"
bad.sh:1:1: "if" must end with "fi" rc=1
Compared with the output in M1 bash -n reports “unexpected end of file on line 3”; shfmt points directly at the unclosed if on line 1.
cd ~/bashlab/opsctl git add -A && git commit -qm "chore: before shfmt" || true
shfmt -f . # list files recognized as Shell (check whether submodules are included; see below) shfmt -d bin/opsctl lib; echo "rc=$?"
shfmt -f . It recurses into test/bats and other submodule directories, so list the files explicitly in the Makefile bin/opsctl lib test/*.bats, and do not format third-party code (or set [test/bats/**] for ignore = true in .editorconfig).
shfmt -l -w bin/opsctl lib git diff --stat git diff bin/opsctl | head -n 20
awk 'length > 80 {printf "%s:%d: %d columns\n", FILENAME, FNR, length}' bin/opsctl lib/*.sh
grep -n '`' bin/opsctl lib/*.sh || echo "no backticks"
ls -l lib/*.sh | awk '{print $1, $NF}' # library files should not have x permission
grep -c '^main "\$@"$' bin/opsctl # should be 1
awk length Counted by character (GNU awk under a UTF-8 locale); Chinese characters take two columns in a terminal, so the 80-column rule is only approximate for Chinese comments.
git commit -qam "style: shfmt" git rev-parse HEAD >> .git-blame-ignore-revs git config blame.ignoreRevsFile .git-blame-ignore-revs
Problem: Half the diff in one ops team's merge request was Tab/space swapping, which made review very inefficient. Approach: Commit once: .editorconfig + run across the whole repository shfmt -w (as a separate commit, and added to .git-blame-ignore-revs), CI adds shfmt -d, and the editor's shfmt plugin formats on save. Result: Format debates disappeared from reviews.
Problem: After adopting shfmt, all lib/*.sh without a shebang reported parse errors, while the entry scripts with a shebang worked fine. Cause: shfmt treats the .sh extension as POSIX. Fix:.editorconfig in [*.sh] shell_variant = bash. Lesson: Read the manual for a tool's “auto-detection” rules.
Problem: A “temporary script” grew to 1,400 lines over three years, including JSON parsing, concurrency and retries. Approach: The team added the Google guide's “consider switching languages for more than 100 lines or complex control flow” to the review checklist; new scripts above the threshold must explain the reason in the PR; the 1,400-line script was migrated to Python following M7's steps.
Cause:.sh the file is parsed as POSIX by default (the error text looks like this; the exact wording depends on your version).
printf '[*.sh]\nshell_variant = bash\n' >> .editorconfig shfmt -ln bash -d lib/log.sh # temporary check (note: EditorConfig is not read when arguments are given)
Cause:① the command line includes -i and other arguments, so EditorConfig is ignored; ② when reading from stdin, there is no --filename; ③ the section's wildcard does not match the file (bin/opsctl has no extension, so it needs its own section).
shfmt -d bin/opsctl # without formatting arguments shfmt --filename=bin/opsctl < bin/opsctl | head
Cause: the local and CI shfmt versions differ (for example, apt's 3.12.0 and the 3.14.1 that CI downloads handle indentation of heredocs nested inside command substitutions differently; 3.14.1 fixed this kind of issue).
Fix: pin the same version locally and in CI; confirm with shfmt --version ; or run locally in a container too mvdan/shfmt:v3.14.1.
Cause: extra spaces used for alignment are not kept by default.
Fix: accept the unified format (recommended), or set keep_padding = true in EditorConfig (-kp).
printf '[vendor/**]\nignore = true\n' >> .editorconfig shfmt -l .
shfmt -d bin/opsctl lib test >/dev/null # check both formatting and syntax # If you only care about syntax: for f in bin/opsctl lib/*.sh; do bash -n "$f" || exit 1; done
Yes. shfmt only handles layout (indentation, spaces, line-break positions). The style guide also specifies conventions that shfmt cannot handle automatically: use [[ ]],$( ),main functions,local separate declaration and assignment, naming conventions (pkg::func, uppercase constants), errors to stderr, library files not executable, avoid eval, and consider switching languages above 100 lines. Part of this is checked by ShellCheck (backticks SC2006, SC2155), and the rest relies on the review checklist. Division of labor: shfmt (formatting) + ShellCheck (semantics) + style guide and review (conventions).
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
shell_variant = bash with one line highlighted; in CI, shfmt -d failing shows the diff.@test → one separate process per test → setup → test body → teardown, and the timing of setup_file/teardown_file .run ($status,$output,${lines[@]},-N,!,--separate-stderr) and bats-assert assertions.$BATS_TEST_TMPDIR to isolate the filesystem, and use “fake commands placed first on PATH” to replace curl and other external dependencies while recording call arguments.run cmd | grep, set -e aborting a test when there is no run, and expected strings starting with -- .bats-core (Bash Automated Testing System) is a Bash test framework compatible with TAP (Test Anything Protocol). Test files end with .bats , and each test is written as @test "description" { … }; the test body is ordinary Bash code, and any command that fails (non-zero exit) makes the test fail— bats enables set -e inside tests (and ERR/DEBUG tracing, used to report the line where the failure happened).
| Component | Purpose | Version in this lesson |
|---|---|---|
| bats-core | Test runner: discovers tests, runs them in isolation, outputs results (pretty / TAP / JUnit) | 1.14.0 (2026-07-21) |
| bats-support | Helper library: unified failure message format (bats-assert depends on it and must be loaded first) | 0.3.0 |
| bats-assert | Assertions: assert_success,assert_failure,assert_output,assert_line,assert_equal,assert_stderr (since 2.2.0), etc. | 2.2.4 |
| bats-file (optional) | File assertions: assert_file_exists , etc. | 0.4.0 |
.bats blocks in each @test "…" { file into ordinary Bash functions and registers the list of tests.setup_file (if defined), and variables set in it export are visible to all tests in that file; finally it runs teardown_file. The whole suite can also have setup_suite.bash.setup → test function → teardown. Variables changed in the test,cd,export PATH all stay out of the next test.skip (setup/teardown also run for skipped tests). A command failing inside teardown does not by itself make the test fail (ERREXIT is turned off in teardown), but teardown returning non-zero does.$BATS_TEST_TMPDIR (file-level $BATS_FILE_TMPDIR, suite-level $BATS_SUITE_TMPDIR), automatically deleted after the run (--no-tempdir-cleanup can be kept for troubleshooting).run cmd args… Runs the command in a subshell— it never makes the test fail because of that command; the results go into variables: $status (exit code),$output (stdout and stderr combined),${lines[@]} (an array per line, empty lines removed by default). With --separate-stderr set, $output contains only stdout, and stderr goes into $stderr / ${stderr_lines[@]}. run -2 cmd requires exit code 2,run ! cmd requires a non-zero exit. Before using these flags you must declare bats_require_minimum_version 1.5.0, otherwise bats prints a BW02 warning.
Because run executes in a subshell,modifications to variables made by functions called inside run are not kept; to check side effects, call the function directly (without run), or check the files it writes. Starting from bats 1.14.0, functions inside run honor your script's set -e (previously shadowed by accident), which is a behavior change to watch out for.
Ops scripts often operate directly on production: deleting files, changing configuration, calling APIs. Without tests, every refactor is a gamble. bats lets you verify in a few seconds: usage and exit code conventions, argument parsing, error paths (missing dependencies, nonexistent files, API failure with retries), output format (downstream scripts depend on it).
The script finds external commands via PATH . In the test's setup , put $BATS_TEST_TMPDIR/bin at the front of PATH, then write an executable fake curl: it appends the received arguments to a file, prints the specified output, and returns a specified exit code. This way the test controls the behavior of external dependencies (success, failure, timeout) and asserts “how many times it was called and with what arguments.” This approach is zero-intrusive for the script, as long as it calls commands by name rather than hard-coding /usr/bin/curl.
| Suitable for bats | Not suitable / find another way |
|---|---|
| CLI contract: usage, exit codes, stdout/stderr separation, output format | End-to-end behavior against real cloud APIs (use integration tests in a staging environment) |
| Argument parsing and error paths | Operations that need root or modify the system (use tests in containers/VMs) |
| Library functions (test directly after source) | Performance (use the M5 benchmarks) |
| Retry, backoff and timeout logic (with doubles and configurable wait times) | UI interaction (read -p and the like; design it to be non-interactive where possible) |
| bats-core | shunit2 | ShellSpec | |
|---|---|---|---|
| Style | @test blocks + plain Bash | xUnit functions (testXxx) | BDD DSL (Describe/It) |
| Target shell | Bash | POSIX sh family | many POSIX shells |
| Ecosystem | Most active; support/assert/file helper libraries; packages available on Ubuntu/Homebrew | Established, lightweight | Built-in mocks, coverage (with kcov) |
run cmd | grep foo ① “Piping run's output into grep checks it”—Bash parses the pipeline first, run's output goes to grep, while run itself produces no output, so the test can pass falsely; use run bats_pipe cmd \| grep foo or run first and then assert_output --partial. ② “a test ! cmd can assert failure”—! cmd does not trigger set -e; only as the last line does it affect the result; use run ! cmd. ③ “$output only has stdout”—by default stdout and stderr are merged. ④ “tests can share a /tmp/test directory”—when run in parallel (--jobs) they step on each other; always use $BATS_TEST_TMPDIR.Choose a scenario and click “Next step”. Above are the lifecycle stages; on the left is the test file (the line being run is highlighted); on the right are the process tree and run the variables captured by run; at the bottom is bats' output. The “introduce bug” scenario creates an off-by-one error in util::retry (one extra try); observe how the test body aborts after an assertion failure, teardown still runs, and how the failure message is formatted. The “forgot to use run” scenario shows how set -e makes the test fail directly. The output format comes from the bats-core 1.14 and bats-assert 2.2.4 docs; details are examples.
| Command / function | Purpose | Notes |
|---|---|---|
bats test/ | Run all .bats in a directory | From 1.14, an error is raised when no tests are found (--allow-empty-suite restores the old behavior) |
bats -f 'health' test/ | Filter by name regex | --filter-tags Filter by tag (# bats test_tags=…) |
bats --tap / -F junit | TAP / JUnit output | --report-formatter junit -o reports/ keeps terminal output too |
bats --jobs 4 | Parallel | requires GNU parallel |
bats --print-output-on-failure | Automatically print $output on failure | recommended in CI |
bats -x / --trace | Print the commands executed within a test | for debugging the tests themselves |
bats --no-tempdir-cleanup | Keep temporary directories | for troubleshooting failing tests |
run [-N|!] [--separate-stderr] cmd | Run and capture | requires bats_require_minimum_version 1.5.0 |
assert_success / assert_failure [N] | check $status | on failure, print status and output |
assert_output [-p|-e] 'x' / refute_output | exact match / contains / regex / no output | when the expected value starts with - , use -- as a separator |
assert_line [--index N] [-p] 'x' | a particular line or any line | empty lines are removed from lines |
assert_equal actual expected | two values are equal | Mind the argument order: actual value first, |
assert_stderr / refute_stderr | then the expected value $stderr | bats-assert ≥ 2.2.0; with --separate-stderr |
load 'path' / bats_load_library name | to load helper files / load libraries via BATS_LIB_PATH | libraries installed by apt are in /usr/lib/bats/ |
skip "reason" | skip the test | can be placed inside an if to skip conditionally |
echo "# msg" >&3 | print debug information in a test | writing to fd 3 makes it appear in the report |
cd ~/bashlab/opsctl
cat > test/test_helper/common.bash <<'EOF'
# test/test_helper/common.bash — setup and test doubles shared by all .bats files
_common_setup() {
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
PROJECT_ROOT=$(cd "${BATS_TEST_DIRNAME}/.." && pwd)
OPSCTL="${PROJECT_ROOT}/bin/opsctl"
# Isolate the developer environment: priority is command line > environment variable OPSCTL_<KEY> > config file > default,
# A leftover OPSCTL_ENV / OPSCTL_HEALTH_RETRIES can make tests that “pass no options” produce completely different results
local v
for v in $(compgen -v OPSCTL_); do unset "${v}"; done
unset LOG_LEVEL RETRY_MAX_DELAY
export NO_COLOR=1 # no color codes in logs, so assertions are simpler
export OPSCTL_DATA_DIR="${BATS_TEST_DIRNAME}/fixtures/data"
STUB_BIN="${BATS_TEST_TMPDIR}/bin"
mkdir -p "${STUB_BIN}"
export PATH="${STUB_BIN}:${PATH}" # put the stub directory at the front of PATH
stub sleep 0 # retry backoff does not really wait, but still records the wait duration
}
# stub <command name> <exit code> [stdout content]
# Generate a fake command: record its arguments to $BATS_TEST_TMPDIR/<command name>.calls, print the content, and return the exit code
stub() {
local name=$1 rc=$2 out=${3:-}
cat >"${STUB_BIN}/${name}" <<STUB
#!/usr/bin/env bash
printf '%s\n' "\$*" >>"${BATS_TEST_TMPDIR}/${name}.calls"
printf '%s' '${out}'
exit ${rc}
STUB
chmod +x "${STUB_BIN}/${name}"
}
# calls <command name>: print all calls received by the stub (one per line)
calls() { cat "${BATS_TEST_TMPDIR}/$1.calls" 2>/dev/null || true; }
EOF
The heredoc end marker STUB is unquoted, so ${BATS_TEST_TMPDIR},${out},${rc} inside generates the fake command, they are expanded and hard-coded into the file; \$* is escaped and left to be expanded when the fake command runs at runtime. out Cannot contain single quotes (simplified for the demo). compgen -v OPSCTL_ Lists all variables starting with OPSCTL_ — test processes are independent, so unset does not affect your terminal. Why also replace sleep ? v0.3's cmd::health retries via Lesson 4's util::retry : after the n-th failure, wait a random duration between 0 and [0, 2n-1] seconds (exponential backoff + full jitter, cap RETRY_MAX_DELAY ; default 30). With the replacement the test finishes instantly, and it can also assert that the wait time did not exceed the upper bound.
health::probe Use curl -sS -o /dev/null -w '%{http_code} %{time_total}' to get “status code, elapsed time”, so the stub must print output like 200 0.012 ; the result is written only to the log (stderr), and stdout is empty.
cat > test/health.bats <<'EOF'
#!/usr/bin/env bats
# test/health.bats — behavior tests for opsctl health (the contract of cmd::health / health::probe from Lesson 6)
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
}
@test "health: missing URL is a usage error (2)" {
run "${OPSCTL}" health
assert_failure 2
assert_output --partial 'missing URL'
}
@test "health: non-http(s) URL is a usage error (2)" {
run "${OPSCTL}" health ftp://web-prod-1/
assert_failure 2
assert_output --partial 'URL must start with http://'
}
@test "health: unknown option is a usage error (2)" {
run "${OPSCTL}" health -x http://web-prod-1/healthz
assert_failure 2
}
@test "health: on 200 succeeds, calls curl only once, stdout is empty" {
stub curl 0 '200 0.012'
run --separate-stderr "${OPSCTL}" health http://web-prod-1/healthz
assert_success
refute_output
assert_stderr --partial 'health ok: http://web-prod-1/healthz code=200'
assert_equal "$(calls curl | wc -l)" 1
}
@test "health: after 4 consecutive failures returns 1, backoff waits do not exceed 1, 2, 4 seconds" {
stub curl 7
run "${OPSCTL}" health -r 4 http://web-prod-1/healthz
assert_failure 1
assert_output --partial 'giving up after 4 attempts'
assert_equal "$(calls curl | wc -l)" 4
local i=0 bound=1 s
while read -r s; do # full jitter: the n-th wait ∈ [0, 2^(n-1)]
((++i))
awk -v s="${s}" -v b="${bound}" 'BEGIN { exit !(s >= 0 && s <= b) }' \
|| fail "wait ${s}s for attempt ${i} exceeds the upper bound ${bound}s"
bound=$((bound * 2))
done < <(calls sleep)
assert_equal "${i}" 3
}
@test "health: unexpected status code (503) also counts as failure, OPSCTL_HEALTH_RETRIES takes effect" {
stub curl 0 '503 0.010'
OPSCTL_HEALTH_RETRIES=2 run "${OPSCTL}" health http://web-prod-1/healthz
assert_failure 1
assert_output --partial 'code=503'
assert_equal "$(calls curl | wc -l)" 2
}
@test "health: command-line -r takes precedence over OPSCTL_HEALTH_RETRIES" {
stub curl 7
OPSCTL_HEALTH_RETRIES=5 run "${OPSCTL}" health -r 2 http://web-prod-1/healthz
assert_failure 1
assert_equal "$(calls curl | wc -l)" 2
}
@test "health: -e sets the expected status code" {
stub curl 0 '204 0.005'
run "${OPSCTL}" health -e 204 http://web-prod-1/healthz
assert_success
}
@test "health: -t passes the connect and total timeouts to curl" {
stub curl 0 '200 0.010'
run "${OPSCTL}" health -t 3 http://web-prod-1/healthz
assert_success
[[ "$(calls curl)" == *'--connect-timeout 3 --max-time 6 -- http://web-prod-1/healthz'* ]]
}
EOF
test/bats/bin/bats test/health.bats
health.bats ✓ health: missing URL is a usage error (2) ✓ health: non-http(s) URL is a usage error (2) ✓ health: unknown option is a usage error (2) ✓ health: on 200 succeeds, calls curl only once, stdout is empty ✓ health: after 4 consecutive failures returns 1, backoff waits do not exceed 1, 2, 4 seconds ✓ health: unexpected status code (503) also counts as failure, OPSCTL_HEALTH_RETRIES takes effect ✓ health: command-line -r takes precedence over OPSCTL_HEALTH_RETRIES ✓ health: -e sets the expected status code ✓ health: -t passes the connect and total timeouts to curl 9 tests, 0 failures
The behavior behind each assertion was checked by running the rebuilt v0.3.0 directly on this machine with the same stubs: exit codes 2/1/0, the log health ok: … code=200,code=503,giving up after 4 attempts, curl arguments --connect-timeout 3 --max-time 6 -- URL,OPSCTL_HEALTH_RETRIES=2 2 calls when -r 2 overrides OPSCTL_HEALTH_RETRIES=5, three waits such as 0.403,0.949,1.648 (random, but all within 1, 2, 4). bats itself was not run in the authoring environment. OPSCTL_HEALTH_RETRIES=2 run … Note: adding a variable prefix to a shell function (run is a function) makes Bash set that variable temporarily while the function runs and export it to child processes.
test/bats/bin/bats --tap test/ mkdir -p reports && test/bats/bin/bats --report-formatter junit --output reports test/
1..9 ok 1 health: missing URL is a usage error (2) ok 2 health: non-http(s) URL is a usage error (2) ok 3 health: unknown option is a usage error (2) ok 4 health: on 200 succeeds, calls curl only once, stdout is empty ok 5 health: after 4 consecutive failures returns 1, backoff waits do not exceed 1, 2, 4 seconds ok 6 health: unexpected status code (503) also counts as failure, OPSCTL_HEALTH_RETRIES takes effect ok 7 health: command-line -r takes precedence over OPSCTL_HEALTH_RETRIES ok 8 health: -e sets the expected status code ok 9 health: -t passes the connect and total timeouts to curl
# Wrong: the pipe is outside run; grep reads empty input, so the test may falsely pass or fail
run "${OPSCTL}" servers list | grep -q web-prod-1
# Right: run first, then assert on $output
run "${OPSCTL}" servers list
assert_output --partial web-prod-1
# Right: when a pipe is really needed (bats ≥ 1.10), note that \| must be escaped
run bats_pipe "${OPSCTL}" servers list \| grep -c prod
VERSION and the fixture test/fixtures/data/servers.csv), step 3 (submodules), and sections 1 and 2 of the Commands page (common.bash,health.bats).test/opsctl.bats (corresponding to opsctl::main,servers list and configuration precedence):
cd ~/bashlab/opsctl
cat > test/opsctl.bats <<'EOF'
#!/usr/bin/env bats
# test/opsctl.bats — contract tests for the entry point, help, servers list and configuration precedence
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
}
@test "--help: prints usage and returns 0" {
run "${OPSCTL}" --help
assert_success
assert_line --index 0 --partial 'ops toolbox for ~/bashlab'
}
@test "no arguments: usage goes to stderr, exit code 2" {
run --separate-stderr "${OPSCTL}"
assert_failure 2
refute_output
assert_stderr --partial 'Usage:'
}
@test "-V: matches the VERSION file" {
run "${OPSCTL}" -V
assert_success
assert_output "opsctl $(<"${PROJECT_ROOT}/VERSION")"
}
@test "unknown subcommand: exit code 2, stdout is empty" {
run --separate-stderr "${OPSCTL}" nope
assert_failure 2
refute_output
assert_stderr --partial 'unknown command: nope'
}
@test "every subcommand has opsctl-summary, and help <name> returns 0" {
local f name
for f in "${PROJECT_ROOT}"/lib/cmd_*.sh; do
name=${f##*/cmd_}
name=${name%.sh}
grep -q '^# opsctl-summary: ' "${f}" || fail "${f##*/} is missing # opsctl-summary:"
run "${OPSCTL}" help "${name}"
assert_success
done
}
@test "servers list --env prod -o tsv: lists only prod, fields with quoted commas are complete" {
run "${OPSCTL}" servers list --env prod -o tsv
assert_success
assert_equal "${#lines[@]}" 2
assert_line --index 0 $'web-prod-1\tprod\tcanadacentral\t10.0.3.10\tweb'
assert_line --index 1 --partial $'\tdb,primary'
}
@test "servers list --env all: the table has a header row" {
run "${OPSCTL}" servers list --env all
assert_success
assert_line --index 0 --regexp '^NAME +ENV +REGION +IP +ROLE$'
assert_equal "${#lines[@]}" 5
}
@test "servers list --env qa: usage error 2" {
run "${OPSCTL}" servers list --env qa
assert_failure 2
assert_output --partial "invalid env 'qa'"
}
@test "servers list --env with missing argument: usage error 2" {
run "${OPSCTL}" servers list --env
assert_failure 2
assert_output --partial "option '--env' requires an argument"
}
@test "precedence: command-line --env overrides OPSCTL_ENV, and no warning by default" {
OPSCTL_ENV=dev run --separate-stderr "${OPSCTL}" servers list --env prod -o tsv
assert_success
assert_output --partial 'web-prod-1'
refute_output --partial 'web-dev-1'
refute_stderr
}
@test "precedence: without --env, OPSCTL_ENV is used; with -v, DEBUG prints the override" {
OPSCTL_ENV=dev run "${OPSCTL}" servers list -o tsv
assert_success
assert_output $'web-dev-1\tdev\tcanadacentral\t10.0.1.10\tweb'
OPSCTL_ENV=dev run --separate-stderr "${OPSCTL}" -v servers list --env prod -o tsv
assert_stderr --partial "flag value 'prod' overrides OPSCTL_ENV=dev"
}
@test "servers list: returns 1 when the data directory is unreadable" {
OPSCTL_DATA_DIR="${BATS_TEST_TMPDIR}/none" run "${OPSCTL}" servers list
assert_failure 1
assert_output --partial 'cannot read'
}
EOF
test/bats/bin/bats test/opsctl.bats
opsctl.bats ✓ --help: prints usage and returns 0 ✓ no arguments: usage goes to stderr, exit code 2 ✓ -V: matches the VERSION file ✓ unknown subcommand: exit code 2, stdout is empty ✓ every subcommand has opsctl-summary, and help <name> returns 0 ✓ servers list --env prod -o tsv: lists only prod, fields with quoted commas are complete ... 12 tests, 0 failures
The two precedence tests correspond to Lesson 3's rule “command line > environment variable > config file > default”: when the command line overrides a different environment variable value, at the default log level stderr is completely empty (refute_stderr), and only when -v is used does DEBUG … flag value 'prod' overrides OPSCTL_ENV=dev appear (measured on this machine). The summary test passes on the rebuilt v0.3.0 (8 cmd_*.sh subcommands all have a summary,help <name> and all return 0). Its value shows up in the future: if someone adds a new lib/cmd_cleanup.sh but forgets the # opsctl-summary: on line two, the help text for that command opsctl --help would be empty — this test then fails immediately with cmd_cleanup.sh is missing # opsctl-summary: (you will verify this yourself in the capstone lab).
test/util.bats (call after source, bypassing the entry point):
cat > test/util.bats <<'EOF'
#!/usr/bin/env bats
# test/util.bats — unit tests for lib/log.sh and lib/util.sh
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
source "${PROJECT_ROOT}/lib/log.sh"
source "${PROJECT_ROOT}/lib/util.sh"
}
@test "util::require_cmd: a missing command exits 3 and lists the missing command" {
run util::require_cmd bash no-such-cmd-xyz
assert_failure 3
assert_output --partial 'missing required command(s): no-such-cmd-xyz'
}
@test "util::csv_split: quoted commas and escaped quotes" {
local -a f
util::csv_split 'db-01,prod,"web,api","say ""hi""",x' f
assert_equal "${#f[@]}" 5
assert_equal "${f[2]}" 'web,api'
assert_equal "${f[3]}" 'say "hi"'
}
@test "log::info: writes to stderr, not stdout, includes [PID]" {
run --separate-stderr log::info hello
assert_success
refute_output
assert_stderr --regexp ' INFO +opsctl\[[0-9]+\]: hello$'
}
EOF
util::csv_split Writes results back to the caller's array via nameref, so must not use run (run executes in a subshell, so the array does not return to the test process) — call it directly and assert on the array. The log format time LEVEL opsctl[PID]: message comes from the v0.2 in Lesson 4. log.sh.
test/logs.bats (Lesson 5 Module 8 has already generated access.sample.log and report.expected.tsv):
cat > test/logs.bats <<'EOF'
#!/usr/bin/env bats
# test/logs.bats — contract tests for opsctl logs report (Lesson 5 cmd::logs)
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
FIX="${BATS_TEST_DIRNAME}/fixtures"
}
@test "logs report --format tsv matches the gold standard output byte for byte" {
[[ -r ${FIX}/report.expected.tsv ]] || skip "generate the gold standard file first, per Lesson 5 Module 8"
run "${OPSCTL}" logs report --format tsv "${FIX}/access.sample.log"
assert_success
assert_output "$(<"${FIX}/report.expected.tsv")"
}
@test "logs report: returns 1 when there are no valid lines" {
printf 'garbage line\n' >"${BATS_TEST_TMPDIR}/bad.log"
run "${OPSCTL}" logs report "${BATS_TEST_TMPDIR}/bad.log"
assert_failure 1
assert_output --partial 'no valid log lines'
}
@test "logs report: returns 1 when the file is unreadable" {
run "${OPSCTL}" logs report "${BATS_TEST_TMPDIR}/nope.log"
assert_failure 1
assert_output --partial 'cannot read log file'
}
@test "logs report --top x: usage error 2" {
run "${OPSCTL}" logs report --top x "${FIX}/access.sample.log"
assert_failure 2
assert_output --partial "invalid top 'x'"
}
EOF
test/bats/bin/bats test/
health.bats ✓ health: missing URL is a usage error (2) ... logs.bats ✓ logs report --format tsv matches the gold standard output byte for byte ... opsctl.bats ... util.bats ✓ util::require_cmd: a missing command exits 3 and lists the missing command ✓ util::csv_split: quoted commas and escaped quotes ✓ log::info: writes to stderr, not stdout, includes [PID] 28 tests, 0 failures
The error-path messages of the three tests above (no valid log lines in … (expected combined log format),cannot read log file: …,invalid top 'x' (from flag); expected a positive integer) and the generation/comparison of the gold standard were all actually run against the rebuilt v0.3.0 on this machine. The gold standard test asserts only tsv (the machine format); layout changes to the text report should not make the test fail.
util::retry create an off-by-one error (one extra retry), then rerun:
sed -i 's/(( attempt >= tries ))/(( attempt > tries ))/' lib/util.sh # macOS: sed -i '' test/bats/bin/bats -f 'after 4 consecutive failures' test/health.bats sed -i 's/(( attempt > tries ))/(( attempt >= tries ))/' lib/util.sh # change it back git diff --stat lib/util.sh # should show no changes
health.bats
✗ health: after 4 consecutive failures returns 1, backoff waits do not exceed 1, 2, 4 seconds
(from function `assert_equal' in file test/test_helper/bats-assert/src/assert_equal.bash, line 40,
in test file test/health.bats, line 38)
`assert_equal "$(calls curl | wc -l)" 4' failed
-- values do not equal --
expected : 4
actual : 5
--
1 test, 1 failure
Running the buggy version directly on this machine: curl was called 5 times, yet the log still says giving up after 4 attempts— someone reading only the log will hardly notice, whereas the stub's call count shows it at a glance. This also shows that tests should assert behavior (call counts), not just the output text.
make-data.sh is deterministic, so it can be generated once for the whole file in setup_file :
setup_file() {
[[ -x ${HOME}/bashlab/make-data.sh ]] || skip "no ~/bashlab/make-data.sh"
"${HOME}/bashlab/make-data.sh" "${BATS_FILE_TMPDIR}/data" >/dev/null
export FULL_DATA_DIR="${BATS_FILE_TMPDIR}/data" # the directory name must end with /data (the script's safeguard)
}
@test "full dataset: 6 prod servers" {
OPSCTL_DATA_DIR=${FULL_DATA_DIR} run "${OPSCTL}" servers list --env prod -o tsv
assert_equal "${#lines[@]}" 6
}
Do not export directly OPSCTL_DATA_DIR: _common_setup at the start of every test clears all OPSCTL_* and points back to the small fixture, so pass it under another variable name and set it with a prefix assignment in the test.
test/bats/bin/bats --no-tempdir-cleanup --print-output-on-failure test/health.bats, then look at curl.calls at the path shown in the output.Problem: Someone changed the health check script's backoff to “retry immediately”; during a service restart, 3 retries were exhausted within 50 ms, and the deployment was wrongly judged as failed. Approach: Add a test: the stub sleep records arguments and asserts that N−1 waits really occurred and that the n-th wait does not exceed 2n−1 seconds (backoff with full jitter is random, so assert an upper bound rather than an exact value; you can also assert that the total wait is not 0). Configuration: In the script, sleep is called via PATH, and the test replaces it with stub sleep 0 , so it neither really waits nor loses the ability to assert wait durations.
Problem: A change wrote an info log line to stdout, and the downstream opsctl servers list | xargs … script treated the log as a hostname and tried to SSH to it. Approach: The contract test uses run --separate-stderr and asserts ${#lines[@]} and the content of each line; log::* the unit test for refute_output asserts that stdout is empty. Result: This kind of problem is caught at the PR stage.
Problem: Several tests all write to /tmp/opsctl-test, and when --jobs 4 is enabled they fail randomly. Approach: Switch them all to $BATS_TEST_TMPDIR; put read-only data that must be shared across tests in setup_file and generate it into $BATS_FILE_TMPDIR.
Cause: bats is not installed, or the repository was cloned without pulling submodules.
git submodule update --init --recursive ls test/bats/bin/bats test/test_helper/bats-assert/load.bash
Cause:load relative paths in are resolved against the test file's own directory, but the helper libraries are not there; or apt-installed libraries were loaded using submodule paths.
# Submodule layout: load 'test_helper/bats-support/load' # apt installation (/usr/lib/bats/…): export BATS_LIB_PATH=/usr/lib/bats # set before running bats bats_load_library bats-support bats_load_library bats-assert
Cause: uses run -N,run ! or --separate-stderr, but does not declare the minimum version.
Fix: add bats_require_minimum_version 1.5.0 at the top of the file (outside setup).
Cause: bats-assert parses arguments starting with - as options (the exact error text depends on the actual output).
assert_output --partial -- '--env needs an argument'
Cause: run was not given --separate-stderr, so stderr has already been merged into $output.
Fix:run --separate-stderr cmd, then use assert_stderr; or, without separating them, assert directly on $output .
Cause:① the script uses an absolute path /usr/bin/curl; ② the script resets PATH; ③ Bash's command hash table caches the old path (curl was already called in the same process); ④ the stub file lacks execute permission or a shebang.
type -a curl # in tests, print with echo "# $(type -a curl)" >&3 hash -r # clear the command hash table
opsctl servers list --env dev -o tsv outputs only one line, and its first column is web-dev-1.@test "servers list --env dev" {
run -0 "${OPSCTL}" servers list --env dev -o tsv
assert_equal "${#lines[@]}" 1
assert_output --regexp '^web-dev-1'$'\t'
}curl does not exist, opsctl health exits with 3 (hint: test the library function directly).@test "require_cmd curl missing" {
source "${PROJECT_ROOT}/lib/log.sh"; source "${PROJECT_ROOT}/lib/util.sh"
run util::require_cmd curl-does-not-exist
assert_failure 3
}
# End-to-end version: build a PATH containing only the necessary commands such as bash/awk/dirname (with symlinks), without curldeploy The subcommand calls rsync and systemctl restart. How do you test, without touching the real system, that “when rsync fails, the service is not restarted and it rolls back”?① in setup, put $BATS_TEST_TMPDIR/bin first in PATH; ② stub rsync 23 (simulating a partial transfer failure),stub systemctl 0; ③ the deployment directory and the current symlink both point to $BATS_TEST_TMPDIR (the script needs to get these paths from variables or a config file; this is exactly “designing for testability”); ④ assert: assert_failure,calls systemctl is empty (assert_equal "$(calls systemctl)" ""),readlink current still points to the old version; ⑤ also write a test where rsync succeeds, and assert that systemctl received restart myapp. If the script needs sudo, also make sudo a stub (exec "$@").
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
$(…), pipelines and external commands are costly inside loops (fork + exec + wait), and count how many processes each iteration of a piece of code creates.[[ =~ ]],printf -v,$(<file),mapfile,read and so on.time/TIMEFORMAT,EPOCHREALTIME, hyperfine,strace -c -f to measure performance rather than guessing.Running a builtin (printf,[[,read, parameter expansion, arithmetic) is just one function call inside the interpreter, on the order of microseconds. Running an external command requires: fork() (copying the process) → child process execve() (loading the new program, dynamic linking, initializing the locale) → parent process wait(). On Linux this is typically about one millisecond, while on Git Bash / Cygwin on Windows (where fork has to be emulated) it can reach tens of milliseconds. Command substitution $(…) and each segment of a pipeline must fork at least one subshell.
| Way of writing | Processes per iteration | Alternative (0 processes) |
|---|---|---|
b=$(basename "$f") | 2 (subshell + basename) | b=${f##*/} |
d=$(dirname "$f") | 2 | d=${f%/*} (note the boundary case when there is no slash) |
ext=$(echo "$f" | sed 's/.*\.//') | 3 (subshell + echo subshell + sed) | ext=${f##*.} |
up=$(echo "$s" | tr a-z A-Z) | 3 | up=${s^^} (Bash ≥ 4) |
n=$(expr $n + 1) | 2 | ((++n)) |
ts=$(date +%F) | 2 | printf -v ts '%(%F)T' -1 (Bash ≥ 4.2) |
c=$(cat file) | 2 | c=$(<file) (1 subshell, no exec) |
if echo "$s" | grep -q '^v[0-9]' | 2–3 | [[ $s =~ ^v[0-9] ]] |
len=$(echo -n "$s" | wc -c) | 3 | ${#s} (character count) |
cmd | while read … | A loop in a subshell loses its variables | while read … done < <(cmd) or shopt -s lastpipe |
Processing a 1000-line access log, using $(echo | cut | cut) to get the status code on each line: about 4000 fork/exec. Measured on this machine (Git Bash 5.2 on Windows): 75 seconds; the same logic using parameter expansion takes only 0.19 seconds; a single awk takes only 0.04 seconds. On Linux the absolute gap is much smaller (fork is cheap), but the ratio still exists, and it grows with data volume.
[[ ]],(( )),printf -v,read,mapfile).find … -exec cmd {} +,xargs -0 -n 100, merging N calls into N/100 calls; when you need parallelism, use xargs -P or GNU parallel.Bash 5.3 added command substitution that runs in the current shell without forking: ${ cmd; } (capture stdout) and ${| cmd; } (get the value of REPLY ). They eliminate the fork of function-style command substitution, but only Bash 5.3+ supports them, so add a version guard (M6) before using them in scripts that must stay compatible with older versions.
time, hyperfine), then optimize the hotspots; after optimizing, use tests (M4) to make sure the results stay the same.| Tool | What it measures | Advantages | Notes |
|---|---|---|---|
time (keyword) | real/user/sys for a pipeline | builtin; can time functions and pipelines; TIMEFORMAT custom | single measurement, large variance |
/usr/bin/time -v | maximum memory and context switches of external programs | resource details | cannot time shell functions |
EPOCHREALTIME | elapsed time between any two points in the script | no fork, microsecond resolution (Bash ≥ 5.0) | the value is a string with a decimal point; strip the decimal point before arithmetic |
| hyperfine | statistics across multiple runs (mean ± standard deviation) | warm-up, comparing multiple commands, exporting Markdown/JSON | measures the whole command (including shell startup) |
strace -c -f | number of system calls (clone/execve) | counts fork calls directly | significant overhead; only for diagnosis |
| xtrace with timestamps (PS4) | per-line timing | locate the slow line (M1) | high overhead, results skewed high |
[ is faster than [[ only because it is simpler”—both are builtins, and the difference is negligible; choosing [[ is for correctness. ② “echo does not fork inside command substitution”—$(echo x | cut …) command substitution itself forks a subshell, and each pipeline segment forks again. ③ “Optimizing means writing everything on one line”—readability drops while performance barely changes; the key is reducing the number of processes per iteration. ④ “Under set -e, ((n++)) is safe”—when n is 0, the value of ((n++)) is 0 and returns 1, which exits the script; count with ((++n)) or n=$((n + 1)).Task: count the lines with 5xx responses in access.log. Choose a method, the number of lines, and the “cost per fork/exec” (about 0.5–1 ms on Linux; measured about 18–25 ms on this machine's Git Bash), then click “Run”: process boxes are generated line by line above (only the first 30 lines are drawn), and the counter below accumulates the process count and estimates the total time. The real measured values for the three methods are on the “Commands” page.
| Command | Purpose | Notes |
|---|---|---|
time cmd / TIMEFORMAT='%R s' | Timing (keyword; can time functions and pipelines) | %R real,%U user,%S sys,%P CPU percentage |
hyperfine -w 3 'cmd1' 'cmd2' | Statistical comparison | -N does not go through the shell; --export-markdown |
strace -f -c -e trace=process bash x.sh | count clone/execve calls | needs strace; for diagnosis only |
t0=$EPOCHREALTIME | microsecond timestamp (Bash ≥ 5.0) | compute differences: do integer arithmetic after removing the decimal point |
printf -v var fmt … | assign the formatted result directly to a variable | instead of var=$(printf …) |
mapfile -t arr < file | read the whole file into an array | instead of line by line arr+=("$(…)"); Bash ≥ 4.0 |
[[ $s =~ re ]]; ${BASH_REMATCH[1]} | regex matching and capture | instead of echo | grep | sed |
cd ~/bashlab/m7
cp ~/bashlab/data/access.log . 2>/dev/null || \
for i in $(seq 1 1000); do
printf '203.0.113.%d - - [17/Nov/2026:10:00:01 +0000] "GET /api/orders HTTP/1.1" %d 512 "-" "curl/8.12.1"\n' \
$((i % 50)) $((i % 10 == 0 ? 500 : 200))
done > access.log
cat > perf.sh <<'EOF'
slow() { # 4 processes per line
local n=0 line code
while IFS= read -r line; do
code=$(echo "$line" | cut -d'"' -f3 | cut -d' ' -f2)
if [ "$code" = 500 ]; then n=$((n + 1)); fi
done < access.log
echo "5xx=$n"
}
fast() { # 0 processes: parameter expansion + [[ ]]
local n=0 line rest code
while IFS= read -r line; do
rest=${line#*\" } # strip up to the first '" ' (end of the request line)
code=${rest%% *} # take the first field: the status code
[[ ${code} == 5?? ]] && ((++n))
done < access.log
echo "5xx=$n"
}
awkv() { # 1 process for the whole file
awk '$9 ~ /^5/ {n++} END {print "5xx=" n+0}' access.log
}
TIMEFORMAT='%R s'
time slow; time fast; time awkv
EOF
bash perf.sh
5xx=100 75.095 s 5xx=100 0.187 s 5xx=100 0.036 s
On Linux (for example in the linuxlab VM),slow typically on the order of seconds,fast and awkv in tens to hundreds of milliseconds (example; actual values vary) — but the ordering stays the same. Lesson 5's access.log if the format differs, the counts will differ.
sed -i 's/^time slow; time fast; time awkv$/"${1:-fast}"/' perf.sh # change it to run only one approach, chosen by argument
strace -f -c -e trace=clone,clone3,execve bash perf.sh slow 2>&1 | tail -n 6
hyperfine -w 2 'bash perf.sh fast' 'bash perf.sh awkv'
% time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- ... 2001 execve ... 4000 clone Benchmark 1: bash perf.sh fast Time (mean ± σ): 48.3 ms ± 1.2 ms [User: 41.0 ms, System: 6.9 ms] Benchmark 2: bash perf.sh awkv Time (mean ± σ): 4.1 ms ± 0.3 ms Summary bash perf.sh awkv ran 11.78 ± 0.94 times faster than bash perf.sh fast
Modern glibc's fork goes through clone/clone3 system calls, so trace them together. The exact count is slightly lower than the theoretical value because Bash optimizes “last pipeline segment runs exec directly”.
t0=$EPOCHREALTIME
fast >/dev/null
t1=$EPOCHREALTIME
echo "elapsed: $(( (${t1/./} - ${t0/./}) / 1000 )) ms"
elapsed: 181 ms
${t1/./} Remove the decimal point, turning “seconds.microseconds” into an integer number of microseconds (both have the same number of decimal places, 6). In some locales the decimal point may be a comma, so production code can use ${t1//[!0-9]/}.
f=/var/log/nginx/access.log.1.gz
echo "${f##*/}" "${f%/*}" "${f##*.}" "${f%.gz}" # basename / dirname / extension / strip suffix
s="Hello World"; echo "${s^^}" "${s,,}" "${#s}" "${s// /_}" # case / length / replace
printf -v today '%(%F)T' -1; echo "$today" # no fork of date
[[ "v1.2.3" =~ ^v([0-9]+)\.([0-9]+) ]] && echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}"
mapfile -t hosts < <(cut -d, -f1 ~/bashlab/data/servers.csv); echo "${#hosts[@]} lines"
cd ~/bashlab/opsctl TIMEFORMAT='%R s' time bin/opsctl logs report ~/bashlab/data/access.log > /tmp/report-before.txt
If your Lesson 5 logs report is already implemented in awk, the baseline is already fast — so use the perf.sh above for this lab.
OPSCTL_TRACE=/tmp/report.trace bin/opsctl logs report ~/bashlab/data/access.log >/dev/null
awk '{print $3}' /tmp/report.trace | sort | uniq -c | sort -rn | head -5 # column 3 is file:line:functionstrace -f -c -e trace=clone,clone3,execve bin/opsctl logs report ~/bashlab/data/access.log >/dev/null. Goal: the number of execve calls should be unrelated to the number of input lines.$(…),echo | cut,date with parameter expansion,[[ =~ ]],printf -v; or replace the whole loop with one awk program.time bin/opsctl logs report ~/bashlab/data/access.log > /tmp/report-after.txt diff -u /tmp/report-before.txt /tmp/report-after.txt && echo "output is identical"
Write this cross-check as a bats test (fixed fixture log + expected output file), so that no future “optimization” silently changes the report.
Problem: A billing script that runs hourly read 2 million log lines one by one, calling $(echo $line | awk '{print $7}') and $(date -d …) on each line; it ran for over an hour, and the jobs started to overlap. Approach: The whole parsing was changed to one awk program (time conversion uses GNU awk's mktime), and Bash only handles arguments, locking and upload. Result: 40 minutes → 20 seconds. Limitation:mktime is a gawk extension and is not available on mawk/BusyBox awk (M6).
Problem: The same bats test suite took 30 seconds on Linux CI and 8 minutes in the developer's Git Bash. Cause: fork has to be emulated on Windows, so its cost is an order of magnitude higher. Approach: Reduce command substitutions in tests; developers are advised to run tests in WSL2 or a container (docker run --rm -v "$PWD":/code bats/bats:1.14.0 test).
Problem: A cleanup script runs one command per file over 300,000 files, using rm. Approach:find "$dir" -type f -mtime +30 -delete (no external rm needed); when other commands are needed, use -exec cmd {} +. Result: 300,000 exec → 0 (-delete) or a few hundred (+).
Cause: the arithmetic command (( expr )) returns 1 when the expression's value is 0. n++ The value of is n before the increment, so it is 0 the first time.
((++n)) # value is the incremented n (≥ 1), returns 0 n=$((n + 1)) # assignment statement, always returns 0
Cause:cmd | while read … The loop after the pipe runs in a subshell (Lesson 2).
while IFS= read -r line; do ((++n)); done < <(cmd) # process substitution # or: shopt -s lastpipe (only takes effect when job control is off, i.e. in scripts)
Cause: the number of processes hit the limit (ulimit -u or the cgroup's pids.max), usually from unlimited background launches in a loop with &, or too many forks.
ulimit -u; cat /sys/fs/cgroup/$(awk -F: '$1=="0"{print $3}' /proc/self/cgroup)/pids.max 2>/dev/null
xargs -P 8 -n 1 cmd < list.txt # use a fixed concurrency level instead of unlimited &Cause: using an external /usr/bin/printf (for example env printf,xargs printf), or running on Bash < 4.2 (such as the 3.2 that ships with macOS). %(…)T It is only available in Bash's builtin printf.
Fix: make sure it is called as a builtin in Bash ≥ 4.2; when compatibility with 3.2 is needed, fall back to date (and accept the fork cost).
/srv/app/releases/2026-11-17_1200.tar.gz into directory, file name, and the version number with .tar.gz removed.p=/srv/app/releases/2026-11-17_1200.tar.gz
dir=${p%/*}; file=${p##*/}; ver=${file%.tar.gz}
printf '%s\n' "$dir" "$file" "$ver"basename and parameter expansion in a 300-iteration loop.f=/var/log/nginx/access.log; TIMEFORMAT='%R s'
time for i in {1..300}; do b=$(basename "$f"); done
time for i in {1..300}; do b=${f##*/}; done
# Measured on this machine with Git Bash: 7.394 s vs 0.002 sssh host uptime, and serially it takes 6 hours. A colleague suggests “replacing ssh with a builtin would make it fast”. How would you analyze this?The bottleneck here is network round trips and remote execution (I/O wait), not the local fork cost — ssh cannot be replaced by a builtin. The right directions: ① parallelism: xargs -P 50 -I{} ssh -o ConnectTimeout=5 -o BatchMode=yes {} uptime or GNU parallel, combined with timeouts; ② reuse connections (ControlMaster); ③ going further, this is already “large-scale remote execution”, which should use Ansible (forks, inventory, result aggregation) or a dedicated monitoring system to collect load (the “switch tools” signal from M7).
No verified English video specifically on Bash performance optimization (replacing external commands with builtins, hyperfine) was found; refer to the storyboard below and the official docs.
${ cmd; })This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
$(echo | cut | cut), with four process boxes popping up on screen on each loop iteration while the counter climbs quickly./bin/sh), Bash's POSIX mode, BusyBox ash, and the Bash 3.2 that ships with macOS.checkbashisms,shellcheck -s sh,dash -n and containers (bash:3.2,busybox:1.37).| System | /bin/sh actually is | bash | Notes |
|---|---|---|---|
| Ubuntu 26.04 / Debian 13 | dash 0.5.12 | 5.3 (Ubuntu) | dash starts fast and closely follows POSIX; system scripts (such as init scripts and maintainer scripts) use sh |
| RHEL / Fedora / Rocky | bash (when started under the name sh, it enters POSIX mode) | 5.x | “It runs on CentOS” does not mean POSIX-compatible |
| Alpine and most minimal container images | BusyBox ash | not present by default (needs apk add bash) | Official bash:* images are also based on Alpine: user-space tools are BusyBox |
| macOS | provided by the system's Bash 3.2 in POSIX mode (can be switched to dash) | 3.2.57 (a 2007 version, not upgraded due to GPLv3 licensing); since Catalina the default interactive shell is zsh | newer Bash installed via Homebrew is in /opt/homebrew/bin/bash |
| Git for Windows | bash (MSYS2) | 5.2.x | one of the test environments used in this lesson |
| Bash form | dash's reaction (measured) | POSIX form |
|---|---|---|
[[ $a == b* ]] | [[: not found | case $a in b*) … ;; esac |
arr=(a b) | Syntax error: "(" unexpected | set -- a b (positional parameters) or a newline-separated string |
function f { … } | Syntax error: "}" unexpected | f() { … } |
source file | source: not found | . ./file |
echo -e "a\tb" | output -e a<Tab>b | printf 'a\tb\n' |
${x^^},${x:1:2},${x/l/L} | Bad substitution | tr,cut,sed, or ${x#…}/${x%…} |
$((2**10)) | arithmetic expression: expecting primary | loop multiplication, or awk |
cat <<< hi | Syntax error: redirection unexpected | printf '%s\n' hi | cat |
cmd &> f | silently parsed as cmd & + > f: run in the background and empty f | cmd >f 2>&1 |
echo {1..3} / $RANDOM | printed as-is {1..3} / empty string | seq 1 3 / awk 'BEGIN{srand();print int(rand()*32768)}' |
set -o pipefail | set: Illegal option -o pipefail (dash 0.5.12) | POSIX.1-2024 has added pipefail, and dash 0.5.13 implements it; on older systems you need to split the pipeline and check each part |
local v=1 | fine (dash and ash both support it) | strict POSIX does not define local, but in practice almost all sh implementations support it |
| Feature | Introduced in | Behavior on 3.2 |
|---|---|---|
associative arrays declare -A | 4.0 | declare: -A: invalid option |
mapfile / readarray | 4.0 | mapfile: command not found |
${x,,} / ${x^^} | 4.0 | bad substitution |
|&,&>>,globstar (**),coproc,;&/;;&,$BASHPID | 4.0 | syntax error or invalid |
{fd}>file automatic fd allocation,BASH_XTRACEFD | 4.1 | invalid |
printf '%(fmt)T',[[ -v var ]],lastpipe | 4.2 | invalid |
declare -n (nameref),wait -n, negative subscripts ${a[-1]} | 4.3 | invalid |
${x@Q},local -,inherit_errexit; set -u under "${empty[@]}" no longer reports unbound | 4.4 | on 3.2, an empty array + set -u errors out directly |
EPOCHSECONDS / EPOCHREALTIME | 5.0 | empty |
${ cmd; },${| cmd; },GLOBSORT | 5.3 | syntax error / invalid |
This is why the opsctl entry point requires Bash ≥ 4.4 — the reason: lib/log.sh uses declare -gA and printf %(…)T (4.2),util::csv_split and config::get uses nameref local -n (4.3), and Lesson 4's v0.2 entry point added shopt -s inherit_errexit (4.4) and relies on empty arrays being safe under set -u from 4.4 on. Its guard is written as two statements (original Lesson 4 entry point):
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
The first statement uses only POSIX syntax, so dash exits when it reaches it and never parses the next line's (( )) (dash reads, parses and executes one statement at a time); the second runs only in bash, and 3.2 can also parse (( )). Principle: the guard itself must be parseable by the shells it is meant to reject, otherwise old shells report an obscure syntax error before the guard runs. Since v0.2, right after the guard come set -Eeuo pipefail and shopt -s inherit_errexit— they must be placed after the guard so that old Bash sees the clear message first.
BusyBox packs ash and hundreds of stripped-down tools into a single binary. ash supports some bash extensions (depending on compile options, such as parts of [[ ]] ,${x//a/b},${x:1:2},source,<<<), but has no arrays The more common pitfalls are in the tools: BusyBox's sed,grep,date,find,awk options are fewer than GNU's (for example, no full parsing of date -d '2 days ago' , and no gawk mktime/strftime extensions). ShellCheck 0.11.0 added SC2330, which warns specifically about unsupported wildcard matching in BusyBox's [[ ]] .
| Route A: POSIX sh | Route B: explicitly require Bash ≥ X | |
|---|---|---|
| shebang | #!/bin/sh | #!/usr/bin/env bash |
| Suitable for | container entrypoints, install scripts (curl | sh), embedded systems, initramfs, Debian package maintainer scripts | ops tools, CI scripts, developer tools (such as opsctl) |
| check | shellcheck -s sh,checkbashisms, run tests in dash and busybox | version guard + run tests on the minimum version (such as bash:4.4 image) |
| Cost | no arrays,[[ ]],local conveniences beyond | macOS users need to install a newer Bash |
#!/bin/bash , so sh script.sh also works”—explicitly calling with sh will ignores the shebang, so the script is interpreted by dash. ② “I tested #!/bin/sh on my Fedora”—there sh is bash, so most bashisms still run; move to Debian and they break. ③ “#!/bin/bash is the most portable”— /bin/bash does not exist on NixOS and some BSDs, and on macOS it is 3.2; #!/usr/bin/env bash uses the first bash on PATH. ④ “Portability is only about the shell”—sed -i,date -d,readlink -f,grep -P,find -printf differ even more between GNU, BSD (macOS) and BusyBox; the Rust-based coreutils that ship as Ubuntu 26.04's default also have some options and error messages that differ from GNU.Click any cell to see how that feature behaves in that shell and the recommended alternative. Results marked “measured” for dash come from an actual run on this machine (the dash bundled with Git for Windows); Bash 3.2 results are based on the version in which each feature was introduced, per Bash's CHANGES/NEWS; the BusyBox column depends on compile options (the Debian/Ubuntu and official busybox images enable bash-compatible extensions by default); verify with containers yourself.
(after selecting a cell, examples and alternatives are shown)
| Command | Purpose | Notes |
|---|---|---|
checkbashisms script.sh | Check #!/bin/sh bashisms in the script | from Debian devscripts; -x additionally checks extensions that POSIX leaves undefined but are common; -f forces checking of files with a non-sh shebang |
shellcheck -s sh script | check against the POSIX sh dialect | reports SC3xxx; -s dash,-s busybox target specific implementations |
dash -n script / bash --posix -n | parse with the target shell | syntax check only |
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash x.sh | run on Bash 3.2 | simulate macOS's built-in Bash (user space is still BusyBox) |
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh x.sh | run on BusyBox ash | the tools are also all BusyBox versions |
echo "$BASH_VERSION" "${BASH_VERSINFO[0]}" | runtime version | empty when not bash |
ls -l /bin/sh,readlink -f /bin/sh | see what /bin/sh points to | Ubuntu: /bin/sh -> dash |
for s in 'echo -e "a\tb"' 'source /dev/null && echo ok' 'x=abc; echo ${x^^}' 'cat <<< hi' \
'arr=(a b)' 'set -o pipefail && echo pf' 'f(){ local v=1; echo $v; }; f'; do
printf '%-34s => ' "$s"; dash -c "$s" 2>&1 | tr '\n' ' '; echo
done
echo -e "a\tb" => -e a b
source /dev/null && echo ok => dash: 1: source: not found
x=abc; echo ${x^^} => dash: 1: Bad substitution
cat <<< hi => dash: 1: Syntax error: redirection unexpected
arr=(a b) => dash: 1: Syntax error: "(" unexpected
set -o pipefail && echo pf => dash: 1: set: Illegal option -o pipefail
f(){ local v=1; echo $v; }; f => 1
cd ~/bashlab/m7 dash -c 'echo ok &> o.txt; sleep 0.2; echo "[$(cat o.txt)]"'
ok []
echo ok & runs in the background, output goes to the terminal,> o.txt as a standalone empty command that empties the file. No error is reported — this is what makes bashisms most dangerous.
cat > posix-demo.sh <<'EOF' #!/bin/sh name=world if [[ $name == w* ]]; then echo -e "hi\t$name"; fi source ./env.sh files=(a b) EOF checkbashisms posix-demo.sh shellcheck -f gcc posix-demo.sh
possible bashism in posix-demo.sh line 3 (alternative test command ([[ foo ]] should be [ foo ])): if [[ $name == w* ]]; then echo -e "hi\t$name"; fi possible bashism in posix-demo.sh line 3 (echo -e): ... possible bashism in posix-demo.sh line 4 (should be '.', not 'source'): source ./env.sh posix-demo.sh:3:4: warning: In POSIX sh, [[ ]] is undefined. [SC3010] posix-demo.sh:3:28: warning: In POSIX sh, echo flags are undefined. [SC3037] posix-demo.sh:4:1: warning: In POSIX sh, 'source' in place of '.' is undefined. [SC3046] posix-demo.sh:5:7: warning: In POSIX sh, arrays are undefined. [SC3030]
cat > posix-ok.sh <<'EOF' #!/bin/sh name=world case $name in w*) printf 'hi\t%s\n' "$name" ;; esac . ./env.sh 2>/dev/null || : set -- a b # use positional parameters instead of an array for f in "$@"; do printf '%s\n' "$f"; done EOF shellcheck -s sh posix-ok.sh && dash posix-ok.sh
cd ~/bashlab/opsctl sh bin/opsctl help; echo "rc=$?" # on Ubuntu, sh is dash
opsctl: please run with bash, not sh rc=3
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash bin/opsctl help; echo "rc=$?"
opsctl: bash >= 4.4 required (found 3.2.57(1)-release); on macOS: brew install bash rc=3
If you remove the guard and try again, 3.2 first reports shopt -s inherit_errexit (invalid shell option name), and then, at lib/log.sh in declare -gA , gives an obscure error such as declare: -g: invalid option — this is exactly the value of the guard.
docker run --rm -v "$PWD":/code -w /code bash:4.4 bash test/bats/bin/bats test/ docker run --rm -v "$PWD":/code -w /code bash:5.3 bash test/bats/bin/bats test/
bash:4.4 (4.4.23),bash:5.3 image tags were verified on Docker Hub on 2026-11-17. The image is based on Alpine: if the tests or opsctl depend on specific GNU tool options (for example, the one used in Lesson 4 util::lock uses flock, and Lesson 6's backup 's sha256sum,find -printf), this will expose it — a valuable portability test in itself.
cat > install.sh <<'EOF'
#!/bin/sh
# install.sh — install opsctl into PREFIX (default ~/.local); POSIX sh, runs in dash/ash
set -eu
PREFIX=${PREFIX:-$HOME/.local}
src=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$PREFIX/lib/opsctl" "$PREFIX/bin"
cp -R "$src/bin" "$src/lib" "$src/VERSION" "$PREFIX/lib/opsctl/"
ln -sf "$PREFIX/lib/opsctl/bin/opsctl" "$PREFIX/bin/opsctl"
printf 'installed opsctl %s to %s\n' "$(cat "$src/VERSION")" "$PREFIX"
EOF
chmod +x install.sh
shellcheck -s sh install.sh && checkbashisms install.sh && echo "POSIX OK"
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh -c 'PREFIX=/tmp/p sh install.sh && ls -l /tmp/p/bin'
Lesson 3's bin/opsctl uses readlink -f -- "${BASH_SOURCE[0]}" to resolve symlinks first and then compute OPSCTL_HOME, so calls made through a link such as ~/.local/bin/opsctl can still find lib/. readlink -f Available on GNU and BusyBox; macOS has supported it since 12.3 — this is one of the few places in the entry point that depend on external tool behavior, and it is worth documenting in the README.
Problem: After switching the image from debian:13-slim to alpine , the container exits right after starting: /entrypoint.sh: line 5: syntax error: unexpected "(". Cause: The script begins with #!/bin/sh but uses arrays; Alpine's sh is BusyBox ash (no arrays); dash on Debian would also fail, but the image's entry point was bash /entrypoint.sh invoked explicitly. Fix: rewrite the entry point as pure POSIX (using set --), verify in CI with shellcheck -s sh and busybox images.
Problem: The script uses sed -i '' 's/a/b/' f (BSD syntax); on GNU sed, '' is taken as the script and the actual script as a file name. Approach: write it in a form both accept sed -i.bak 's/a/b/' f && rm f.bak, or use perl -pi -e, or ask developers to install GNU sed (gsed). Lesson: Portability is more often a tool problem than a shell problem.
Problem: An internal .deb package's postinst used [[ ]], which worked on developers' machines (where /bin/sh was changed to bash) but failed to install on standard servers. Approach: Add checkbashisms debian/*.postinst debian/*.prerm to the packaging pipeline (Debian's lintian also checks it).
Cause: the script is run by dash (via sh script invocation or #!/bin/sh), but it uses bash syntax.
head -1 script.sh; ls -l /bin/sh bash script.sh # temporary: explicitly use bash # Permanent fix: change the shebang to #!/usr/bin/env bash, add chmod +x and run with ./script.sh; or rewrite the script as POSIX
Cause: using associative arrays in Bash 3.2 (macOS's /bin/bash).
brew install bash command -v bash # confirm /opt/homebrew/bin/bash is first in PATH # the script uses #!/usr/bin/env bash, and adds a version guard
Cause: In Bash < 4.4, under set -u , expanding an empty array "${arr[@]}" reports unbound variable.
"${arr[@]+"${arr[@]}"}" # a form compatible with older versions
# or require Bash ≥ 4.4Cause: the shebang line ends in CRLF, so env looks for a program named bash\r (the carriage return included).
sed -i 's/\r$//' script.sh && git add --renormalize .
Cause:date -d 's free-form parsing is a GNU extension; macOS uses date -v-2d, and BusyBox supports only limited formats.
printf -v d '%(%F)T' "$(( EPOCHSECONDS - 2*86400 ))" # Bash ≥ 5.0, does not depend on the date implementation
if [[ $f == *.log ]]; then echo -e "log:\t$f"; fi as POSIX sh.case $f in *.log) printf 'log:\t%s\n' "$f" ;; esac
if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 5 ]; then
echo "requires Bash >= 5.0 (current ${BASH_VERSION:-not bash})" >&2
exit 3
fi
# In dash ${BASH_VERSINFO:-} is empty, || short-circuits, and the part with the array subscript is never expandedcurl -fsSL https://…/install.sh | sh), which users may run on Ubuntu, Alpine or macOS. How would you design and verify it?① The target is the “innermost ring”: #!/bin/sh + strict POSIX, no arrays,[[ ]],echo -e,source,&>; ② tools use only POSIX options (uname,mkdir -p,cp,printf), detect the platform with uname -s/uname -m; the download tool supports both curl and wget; ③ put all logic inside functions and call main "$@", to prevent “running while still downloading”; ④ verify: shellcheck -s sh,checkbashisms, the CI matrix runs on debian (dash),alpine/busybox (ash),macos-latest ; ⑤ provide checksums or signatures, and document a “download, review, then run” alternative.
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
Bash excels at orchestrating processes: gluing existing command-line tools (git, curl, tar, rsync, kubectl, awk, jq) together with pipes, redirection and exit codes; it starts fast, needs no installation, and is available on every Linux system. It is a good fit as long as the main work is done by external commands and Bash only handles sequencing and error handling.
| # | Signal | Why Bash is not good at it | More suitable |
|---|---|---|---|
| 1 | the script exceeds about 100 lines, or its control flow is not intuitive (the Google style guide's standard) | no module system, no types, and no real scoping; maintenance cost rises non-linearly with line count | Python / Go |
| 2 | needs nested data structures (lists inside dictionaries, arrays of objects) | only one-dimensional indexed arrays and associative arrays (and 3.2 has no associative arrays), with no nesting | Python (dict/list), Go (struct) |
| 3 | heavy reading and writing of JSON/YAML, not just extracting one or two fields | requires jq/yq round trips; quoting and escaping are very error-prone | Python, Go; a few value extractions with jq are fine |
| 4 | floating-point arithmetic, date calculations, precise string handling (Unicode, CSV quoted fields) | only integer arithmetic; relies on bc/date/awk, which differ between implementations (M6) | Python |
| 5 | needs fine-grained error handling (distinguishing error types, retrying with context, cleaning up many kinds of resources) | only 8-bit exit codes and stderr text; set -e complex exception rules (Lesson 4) | Python (exceptions), Go (error values) |
| 6 | concurrency that needs shared state (worker pools, rate limiting, aggregating results) | &/wait -n/xargs -P only suitable for independent tasks | Go (goroutines, channels), Python (concurrent.futures / asyncio) |
| 7 | long-running processes, HTTP services, long-lived daemons | signals, memory, logging and health checks all have to be assembled by hand | Go, or Python + systemd |
| 8 | needs to run natively on Windows, or is distributed to uncontrolled machines | depends on Bash version and GNU/BSD tool differences | Go (a single static binary) |
| 9 | handling untrusted input and concatenating commands (eval,ssh host "$cmd") | high risk of quoting and injection problems; hard to audit | Python (subprocess.run([...]) argument lists), Go (exec.Command) |
| 10 | performance is still insufficient after optimization is exhausted (M5) | interpreted execution: every external command is a fork/exec | Go, Python + suitable libraries |
| 11 | “converge configuration to a desired state across many hosts” | scripts are imperative, hard to make idempotent, and hard to report “what changed” | Ansible(declarative, idempotent, inventories, --check/--diff) |
| 12 | “create and manage the lifecycle of cloud resources” | no state, dependency graph or plan | Terraform |
An out-of-bounds Bash script does not suddenly break; instead it slowly becomes a script nobody dares to change: every change may trigger some quoting, subshell or set -e exception corner case. The migration cost grows over time — the cheapest time to migrate is the first time one of the signals in the table above appears.
opsctl logs report is implemented in Python, and the entry point's cmd::logs is changed to exec python3 "${OPSCTL_HOME}/libexec/logs_report.py" "$@".OPSCTL_IMPL=py) to give it to some users first; once stable, delete the old implementation.argparse/click) or Go (cobra), and Bash keeps only the truly glue parts (such as the install script).| Python | Go | |
|---|---|---|
| distribution | needs an interpreter and dependencies (venv, uv, pipx); the system python3 varies by version | a single static binary, cross-compiled for Linux/macOS/Windows |
| development speed | fast; the standard library covers json, csv, re, pathlib, subprocess, argparse | medium; the type system is stricter |
| concurrency | good I/O concurrency (asyncio, thread pools); CPU concurrency is affected by the GIL (3.13+ has an experimental free-threaded build) | goroutines are native and simple |
| suited to | data processing, reporting, upgraded glue, teams familiar with Python | CLIs distributed to many machines, long-running services, high concurrency |
subprocess.run(..., shell=True) still has injection and quoting problems; pass argument lists instead.Tick the situations that match your script; suggestions and reasons appear on the right in real time. The weights are this lesson's empirical values, not a standard — the goal is to turn “this script feels a bit complicated” into concrete signals that can be discussed.
Task: count the distribution of status codes in an access log, output status code count, sorted by status code; lines that cannot be parsed are skipped and reported on stderr.
awk '$9 ~ /^[0-9][0-9][0-9]$/ {c[$9]++} END {for (k in c) print k, c[k]}' access.log | sort
mkdir -p ~/bashlab/opsctl/libexec
cat > ~/bashlab/opsctl/libexec/logs_report.py <<'EOF'
#!/usr/bin/env python3
"""logs_report.py — count the status-code distribution of an access log (output matches the awk version)."""
import re
import sys
from collections import Counter
LINE = re.compile(r'^\S+ \S+ \S+ \[[^\]]+\] "[^"]*" (\d{3}) ')
def main(argv: list[str]) -> int:
if len(argv) != 2:
print("usage: logs_report.py ACCESS_LOG", file=sys.stderr)
return 2
counts: Counter[str] = Counter()
bad = 0
try:
with open(argv[1], encoding="utf-8", errors="replace") as fh:
for line in fh:
m = LINE.match(line)
if m:
counts[m.group(1)] += 1
else:
bad += 1
except FileNotFoundError:
print(f"file not found: {argv[1]}", file=sys.stderr)
return 1
for code in sorted(counts):
print(f"{code} {counts[code]}")
if bad:
print(f"skipped {bad} unparseable records", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
EOF
chmod +x ~/bashlab/opsctl/libexec/logs_report.py
cd ~/bashlab/m7
python3 ~/bashlab/opsctl/libexec/logs_report.py access.log > py.txt
awk '$9 ~ /^[0-9][0-9][0-9]$/ {c[$9]++} END {for (k in c) print k, c[k]}' access.log | sort > awk.txt
diff -u awk.txt py.txt && echo "output is identical"
python3 ~/bashlab/opsctl/libexec/logs_report.py; echo "rc=$?"
skipped 1 unparseable record 200 900 401 1 500 100 output is identical usage: logs_report.py ACCESS_LOG rc=2
When running Python directly on Windows, stdout uses CRLF line endings by default,diff so every line is reported as different (we hit this on this machine); Linux/macOS do not have this problem, and on Windows you can use diff --strip-trailing-cr. This is a small example of a “cross-platform” signal.
opsctl codes, with both implementations sharing one entry pointLesson 5's logs report (lib/cmd_logs.sh + lib/logs_report.awk) is already a proper awk report and is protected by M4's gold-standard tests, so it does not need migrating; here we create a separate small subcommand codes (status-code distribution) to demonstrate the migration pattern — it follows Lesson 3's conventions (lib/cmd_codes.sh,cmd::codes, and the second line # opsctl-summary:), and runs in v0.2's strict mode without overwriting any file you already have:
cat > ~/bashlab/opsctl/lib/cmd_codes.sh <<'EOF'
# shellcheck shell=bash
# opsctl-summary: HTTP status code distribution of an access log (codes FILE)
# lib/cmd_codes.sh — strangler pattern demo: when OPSCTL_IMPL=py, hand off to the Python implementation
cmd::codes() {
if [[ ${1-} == -h || ${1-} == --help ]]; then
echo "usage: opsctl codes <access.log>"
return 0
fi
local file=${1-}
[[ -n ${file} ]] || util::usage_error "codes: missing <access.log>"
[[ -r ${file} ]] || util::die "codes: cannot read ${file}" 1
if [[ ${OPSCTL_IMPL:-bash} == py ]]; then
util::require_cmd python3
exec python3 "${OPSCTL_HOME}/libexec/logs_report.py" "${file}"
fi
awk '$9 ~ /^[0-9][0-9][0-9]$/ { c[$9]++ } END { for (k in c) print k, c[k] }' "${file}" | sort
}
EOF
cd ~/bashlab/opsctl
bin/opsctl codes test/fixtures/access.log; echo "rc=$?"
bin/opsctl codes /nope; echo "rc=$?"
200 2 401 1 500 1 rc=0 2026-11-17T09:49:07-0500 ERROR opsctl[1837]: codes: cannot read /nope rc=1
opsctl --help command list appears automatically codes (Lesson 3's opsctl::list_commands scan of summary comments). Use exec to replace the process directly with Python: the exit code is Python's, with no extra Bash process layer.
cd ~/bashlab/opsctl cat > test/fixtures/access.log <<'EOF' 203.0.113.7 - - [17/Nov/2026:10:00:01 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1" 203.0.113.8 - - [17/Nov/2026:10:00:02 +0000] "GET /api/orders HTTP/1.1" 500 31 "-" "Mozilla/5.0 (X11; Linux x86_64)" 203.0.113.9 - - [17/Nov/2026:10:00:03 +0000] "POST /login HTTP/1.1" 401 12 "-" "python-requests/2.32" 203.0.113.7 - - [17/Nov/2026:10:00:04 +0000] "GET / HTTP/1.1" 200 512 "-" "curl/8.12.1" EOF
cat > test/codes.bats <<'EOF'
#!/usr/bin/env bats
# test/codes.bats — contract tests for the codes subcommand; the bash and py implementations run the same set of assertions
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/common'
_common_setup
}
assert_codes_report() {
run --separate-stderr "${OPSCTL}" codes "${BATS_TEST_DIRNAME}/fixtures/access.log"
assert_success
assert_output "$(printf '200 2\n401 1\n500 1')"
}
@test "codes (bash implementation)" {
OPSCTL_IMPL=bash assert_codes_report
}
@test "codes (python implementation)" {
command -v python3 >/dev/null || skip "no python3"
OPSCTL_IMPL=py assert_codes_report
}
@test "codes: returns 1 when the file does not exist (both implementations check at the entry point)" {
run "${OPSCTL}" codes /nonexistent.log
assert_failure 1
}
@test "codes: missing argument is a usage error 2" {
run "${OPSCTL}" codes
assert_failure 2
}
@test "cross-check on the full dataset: both implementations produce byte-identical output" {
command -v python3 >/dev/null || skip "no python3"
local log=${HOME}/bashlab/data/access.log
[[ -r ${log} ]] || skip "no access.log from Lesson 1"
diff <(OPSCTL_IMPL=bash "${OPSCTL}" codes "${log}") <(OPSCTL_IMPL=py "${OPSCTL}" codes "${log}" 2>/dev/null)
}
EOF
test/bats/bin/bats test/codes.bats
codes.bats ✓ codes (bash implementation) ✓ codes (python implementation) ✓ codes: returns 1 when the file does not exist (both implementations check at the entry point) ✓ codes: missing argument is a usage error 2 ✓ cross-check on the full dataset: both implementations produce byte-identical output 5 tests, 0 failures
When run directly on this machine (not through bats), the output of both implementations on the fixture is 200 2,401 1,500 1; the only difference is that Python outputs CRLF on Windows — Linux/macOS does not have this. The full access.log from Lesson 1 (611 lines, 28 lines of 5xx: 500×12, 502×4, 503×12) can be used as one last cross-check test. OPSCTL_IMPL=bash assert_codes_report is setting a prefix assignment on the function, so the variable is passed to the opsctl launched by run inside it.
deploy involves multiple hosts, consider Ansible).Problem: A release script parsed a YAML manifest, called 3 APIs, uploaded artifacts concurrently and rolled back on failure; it grew to 1,400 lines, caused 5 incidents over three years, and nobody dared to change it. Approach: First write 40 bats contract tests to freeze the behavior; then migrate subcommand by subcommand to Python (PyYAML for YAML, requests for HTTP, a thread pool for concurrency); within 6 weeks the entry point went from “Bash calling Python” to “pure Python + a thin Bash install script”. Result: Code shrank to 600 lines, with unit tests and type checking, and incidents dropped to zero.
Problem:for h in $(cat hosts); do ssh "$h" "sudo sed -i … && systemctl restart …"; done— failed hosts could not be retried, nobody could tell who changed what, and quoting was nested layer upon layer. Approach: Changed to an Ansible playbook (lineinfile + handler), gaining idempotency,--check --diff dry runs (check mode) and a retry file for failed hosts. See Ansible 8 hours.
Problem: A Bash tool behaved differently on macOS (3.2), Ubuntu and WSL, and supporting it was very expensive. Approach: Rewrite in Go as a single binary, distributed through a package manager; keep the original bats tests as end-to-end tests (bats can test any command-line program).
Cause: line endings (CRLF on Windows), trailing newlines, sort order (sort is affected by locale, while Python's sorted sorts by code point).
diff <(LC_ALL=C sort awk.txt) <(LC_ALL=C sort py.txt) cat -A py.txt | head -3 # ^M$ means CRLF
Cause: the target machine has no Python, or the version is below 3.9.
Fix: in the entry point, use util::require_cmd python3 to exit with code 3; document the minimum version; or switch to Go to produce a static binary.
Cause: used subprocess.run(f"tar czf {name} …", shell=True).
subprocess.run(["tar", "czf", name, "-C", src, "."], check=True) # argument list, does not go through the shell
Cause: An uncaught Python exception exits with code 1 by default, and argparse exits with code 2 on usage errors — which does not fully match the opsctl convention (3 = missing dependency).
Fix: catch exceptions in main() and map them to the agreed exit codes; contract tests cover every exit code.
~/bashlab/data/inventory.json — is this still Bash's sweet spot?jq -r '.[] | select(.env == "prod") | .name' ~/bashlab/data/inventory.json # Answer: one-off value extraction; jq does all the data processing, and Bash is just glue. # If you need to group by region, merge multiple JSON files, and generate new JSON — consider Python.
rsync in Python, and exit with code 1 on failure.import subprocess, sys
r = subprocess.run(["rsync", "-a", "--delete", src + "/", dst], check=False)
if r.returncode != 0:
print(f"rsync failed: {r.returncode}", file=sys.stderr)
sys.exit(1)opsctl report --format json: aggregate health-check results from 50 hosts (concurrently), compute P95 latency, and output nested JSON. Would you keep using Bash?Not recommended. This requirement hits several signals at once: concurrency with aggregation of shared results (#6), floating-point P95 calculation (#4), and generating nested JSON (#2, #3). Suggestion: implement it in Python libexec/report.py (concurrent.futures.ThreadPoolExecutor + statistics.quantiles + json.dumps), dispatched by the Bash entry point; write contract tests with bats (using JSON fixtures and jq -e to assert structure). If opsctl later needs to be distributed to many machines or become a long-running service, evaluate Go.
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
lint,fmt,fmt-check,test,check, and release targets with a Makefile (or justfile), so local and CI run exactly the same commands.VERSION file + git tags + git archive + sha256sum and verify version consistency in CI.For an ops CLI, “1.0” is a promise: usage, exit codes and stdout format are managed by semantic versioning from now on (breaking changes require a major version bump). Keeping this promise needs three things: contract tests (M4) keep behavior unchanged,quality gates (M2, M3) ensure every merged change passes the checks,reproducible releases ensure users get exactly the commit that was tested.
opsctl/
├── VERSION # 1.0.0 (the single source of version)
├── Makefile # lint / fmt / fmt-check / test / check / release
├── justfile # optional: equivalent to the Makefile
├── .editorconfig # shfmt configuration (M3)
├── .shellcheckrc # ShellCheck configuration (M2)
├── .gitattributes # eol=lf; exclude test/ etc. at release
├── .github/
│ ├── workflows/ci.yml # checks + tag-triggered release
│ └── dependabot.yml # automatically updates the pinned action SHAs
├── bin/opsctl # entry point (executable, no extension)
├── lib/ # log.sh util.sh config.sh cmd_*.sh logs_report.awk (not executable)
├── libexec/logs_report.py # Python implementation of the M7 codes subcommand (optional)
├── etc/opsctl.conf
├── var/lock/ # lock files for util::lock (Lesson 4; var/ is already in .gitignore)
├── install.sh # POSIX sh install script (M6)
└── test/
├── bats/ # submodule bats-core v1.14.0
├── test_helper/ # submodules bats-support, bats-assert + common.bash
├── fixtures/ # data/servers.csv access.log access.sample.log report.expected.tsv
├── smoke.sh mockapi.py # Lesson 6 smoke tests (kept)
├── flaky.sh # Lesson 4 demo for util::retry
└── *.bats # opsctl health util logs codes
make check and CI run the same command; the only remaining cause of “passes locally, fails in CI” is the tool version (eliminated by pinning versions).make check (see GitLab,Jenkins courses).| Object | Approach | Reason |
|---|---|---|
| third-party action | uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 | Tags can be moved; commit SHAs cannot. Keep a human-readable version number in a comment; Dependabot updates both the SHA and the comment. |
| tool versions | CI downloads ShellCheck v0.11.0 and shfmt v3.14.1 by version number; bats is pinned to v1.14.0 via a submodule | ubuntu-latest Versions preinstalled on the image change, and new versions may add warnings |
| token permissions | permissions: contents: read; only the release job contents: write; persist-credentials: false | least privilege, so that tampered steps cannot push code |
A stricter approach would also verify the SHA-256 of downloaded files (writing the official release page's checksums into the workflow). For brevity this lesson does not include specific checksums; see the “known limitations” section.
make check).VERSION to 1.0.0, update CHANGELOG, and commit.git tag -a v1.0.0 -m "opsctl 1.0.0" && git push origin v1.0.0.VERSION matches the tag → git archive → sha256sum → create the GitHub Release and upload.sha256sum -c to verify, then runs install.sh.| make | just | |
|---|---|---|
| Preinstalled | almost all Unix-like systems have it | needs to be installed (1.59.0, 2026-10) |
| Syntax pitfalls | recipes must be indented with Tab ; variables $(VAR) are distinguished from Shell's $$var ; each line runs in a separate shell by default | space indentation is fine; {{var}} interpolation; more friendly error messages |
| suited to | needs zero dependencies, or already has the make ecosystem | pure task runner |
uses: actions/checkout@v7 is pinned”—that is a movable tag, not a fixed one. ② “CI uses apt install shellcheck is simplest”—the runner image's repository version differs from local, so results are not reproducible. ③ “Releasing just tars up the working directory”—the working directory may contain uncommitted changes and locally generated files; git archive <tag> packages only the commit the tag points to. ④ “If the tests pass, you can tag”—you also need to confirm VERSION matches the tag and the working tree is clean; the Makefile's release target checks both.Choose a “commit”, click “Push”, and observe the GitHub Actions steps running in order, which step fails, what appears in the log, and how to reproduce it locally. Log content is an example (formatted after each tool's real output).
Recipe lines must start with Tab (the code block below uses a Tab; if your editor converts the Tab to spaces when copying, make will report missing separator).
cat > ~/bashlab/opsctl/Makefile <<'EOF'
# Makefile — opsctl's quality gate and release (shared by local and CI)
SHELL := bash
.SHELLFLAGS := -eu -o pipefail -c
.DEFAULT_GOAL := check
VERSION := $(shell cat VERSION)
SH_FILES := bin/opsctl $(wildcard lib/*.sh)
BATS := test/bats/bin/bats
DIST := dist
TARBALL := $(DIST)/opsctl-$(VERSION).tar.gz
.PHONY: check lint fmt fmt-check test release clean version
check: lint fmt-check test
lint:
shellcheck --version | sed -n 2p
shellcheck $(SH_FILES)
fmt:
shfmt -w $(SH_FILES) test/*.bats
fmt-check:
shfmt -d $(SH_FILES) test/*.bats
test:
$(BATS) --print-output-on-failure test/
version:
@echo $(VERSION)
release: check
@git diff --quiet && git diff --cached --quiet || { echo "working tree is not clean" >&2; exit 1; }
@git rev-parse -q --verify "refs/tags/v$(VERSION)" >/dev/null || { echo "missing tag v$(VERSION)" >&2; exit 1; }
mkdir -p $(DIST)
git archive --format=tar.gz --prefix=opsctl-$(VERSION)/ -o $(TARBALL) v$(VERSION)
cd $(DIST) && sha256sum opsctl-$(VERSION).tar.gz > opsctl-$(VERSION).tar.gz.sha256
@echo "generated $(TARBALL)"
clean:
rm -rf -- $(DIST) reports
EOF
cd ~/bashlab/opsctl && make -n check | head
On macOS there is no sha256sum when using shasum -a 256; GNU make 3.82+ supports .SHELLFLAGS (the make 3.81 built into macOS does not support it; you can brew install make then use gmake).
cat > ~/bashlab/opsctl/justfile <<'EOF'
# justfile — task definitions equivalent to the Makefile (just 1.59.0)
set shell := ["bash", "-euo", "pipefail", "-c"]
version := `cat VERSION`
sh_files := "bin/opsctl lib/*.sh"
default: check
check: lint fmt-check test
lint:
shellcheck {{sh_files}}
fmt:
shfmt -w {{sh_files}} test/*.bats
fmt-check:
shfmt -d {{sh_files}} test/*.bats
test:
test/bats/bin/bats --print-output-on-failure test/
release: check
mkdir -p dist
git archive --format=tar.gz --prefix=opsctl-{{version}}/ -o dist/opsctl-{{version}}.tar.gz v{{version}}
cd dist && sha256sum opsctl-{{version}}.tar.gz > opsctl-{{version}}.tar.gz.sha256
EOF
mkdir -p ~/bashlab/opsctl/.github/workflows
cat > ~/bashlab/opsctl/.github/workflows/ci.yml <<'EOF'
name: ci
on:
push:
branches: [main]
tags: ['v*']
pull_request:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-24.04
timeout-minutes: 10
env:
SHELLCHECK_VERSION: v0.11.0
SHFMT_VERSION: v3.14.1
steps:
- name: Checkout (including bats submodules)
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
submodules: recursive
persist-credentials: false
- name: Install pinned versions of ShellCheck and shfmt
run: |
set -euo pipefail
mkdir -p "$HOME/.local/bin"
curl -fsSL "https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION}/shellcheck-${SHELLCHECK_VERSION}.linux.x86_64.tar.xz" \
| tar -xJ -C "$RUNNER_TEMP"
install -m 0755 "$RUNNER_TEMP/shellcheck-${SHELLCHECK_VERSION}/shellcheck" "$HOME/.local/bin/shellcheck"
curl -fsSLo "$HOME/.local/bin/shfmt" \
"https://github.com/mvdan/sh/releases/download/${SHFMT_VERSION}/shfmt_${SHFMT_VERSION}_linux_amd64"
chmod +x "$HOME/.local/bin/shfmt"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: Tool versions
run: |
bash --version | head -n1
shellcheck --version
shfmt --version
test/bats/bin/bats --version
- name: ShellCheck
run: make lint
- name: shfmt
run: make fmt-check
- name: bats
run: make test
release:
needs: check
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build tarball and checksums
run: |
set -euo pipefail
v=$(<VERSION)
if [[ "v${v}" != "${GITHUB_REF_NAME}" ]]; then
echo "::error::VERSION (${v}) does not match tag (${GITHUB_REF_NAME})"
exit 1
fi
mkdir -p dist
git archive --format=tar.gz --prefix="opsctl-${v}/" -o "dist/opsctl-${v}.tar.gz" "${GITHUB_REF_NAME}"
(cd dist && sha256sum "opsctl-${v}.tar.gz" > "opsctl-${v}.tar.gz.sha256")
- name: Create GitHub Release
env:
GH_TOKEN: ${{ github.token }}
run: gh release create "${GITHUB_REF_NAME}" dist/* --title "opsctl ${GITHUB_REF_NAME}" --generate-notes
EOF
Key points: ① actions/checkout pinned to the commit SHA of v7.0.1 (verified via the GitHub API on 2026-11-17 refs/tags/v7.0.1 → 3d3c42e5…); ② ShellCheck/shfmt download URLs and file names were verified against the asset names on the v0.11.0 and v3.14.1 release pages; ③ runner chosen ubuntu-24.04 rather than ubuntu-latest to avoid changes from image upgrades (it ships with Bash 5.2, which also tests a non-5.3 environment); ④ gh CLI is preinstalled on GitHub-hosted runners. For Actions syntax details see GitHub 8 hours.
cat > ~/bashlab/opsctl/.github/dependabot.yml <<'EOF'
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: gitsubmodule
directory: /
schedule:
interval: monthly
EOF
cat > ~/bashlab/opsctl/.gitattributes <<'EOF'
* text=auto eol=lf
/test export-ignore
/.github export-ignore
/.editorconfig export-ignore
/.shellcheckrc export-ignore
/justfile export-ignore
EOF
export-ignore Let git archive exclude tests and CI files when packaging, so the release contains only what is needed to run.
.shellcheckrc, M3 .editorconfig, and M4 tests):
cd ~/bashlab/opsctl make check
shellcheck --version | sed -n 2p version: 0.11.0 shellcheck bin/opsctl lib/cmd_backup.sh lib/cmd_codes.sh lib/cmd_config.sh lib/cmd_deploy.sh lib/cmd_doctor.sh lib/cmd_export.sh lib/cmd_health.sh lib/cmd_logs.sh lib/cmd_servers.sh lib/config.sh lib/log.sh lib/util.sh shfmt -d bin/opsctl lib/cmd_backup.sh lib/cmd_codes.sh lib/cmd_config.sh lib/cmd_deploy.sh lib/cmd_doctor.sh lib/cmd_export.sh lib/cmd_health.sh lib/cmd_logs.sh lib/cmd_servers.sh lib/config.sh lib/log.sh lib/util.sh test/codes.bats test/health.bats test/logs.bats test/opsctl.bats test/util.bats test/bats/bin/bats --print-output-on-failure test/ health.bats ✓ health: missing URL is a usage error (2) ... 33 tests, 0 failures
If fmt-check fails, run make fmt then commit separately; Lessons 4–6 cmd_export.sh,cmd_doctor.sh,cmd_logs.sh,cmd_backup.sh,cmd_deploy.sh are also checked by ShellCheck and shfmt, and covered by M4's “every subcommand has opsctl-summary” test — this is the meaning of v1.0. In CI you can also add a step that runs Lesson 6's test/smoke.sh (needs python3 to start a mock API) as an end-to-end smoke test. Test count 33 = health 9 + opsctl 12 + util 3 + logs 4 + codes 5 (codes from M7). Note SH_FILES only matches lib/*.sh, Lesson 5's lib/logs_report.awk is not managed by ShellCheck/shfmt; it is protected by logs.bats 's gold-standard tests.
echo 1.0.0 > VERSION bin/opsctl --version git add -A git commit -qm "release: opsctl 1.0.0" git tag -a v1.0.0 -m "opsctl 1.0.0"
make release ls -l dist/ (cd dist && sha256sum -c opsctl-1.0.0.tar.gz.sha256) tar -tzf dist/opsctl-1.0.0.tar.gz | head
opsctl-1.0.0.tar.gz: OK opsctl-1.0.0/ opsctl-1.0.0/.gitattributes opsctl-1.0.0/Makefile opsctl-1.0.0/VERSION opsctl-1.0.0/bin/ opsctl-1.0.0/bin/opsctl opsctl-1.0.0/etc/ ...
rm -rf ~/bashlab/m7/install-test && mkdir -p ~/bashlab/m7/install-test tar -xzf dist/opsctl-1.0.0.tar.gz -C ~/bashlab/m7/install-test ~/bashlab/m7/install-test/opsctl-1.0.0/bin/opsctl --version
opsctl 1.0.0
git remote add origin git@github.com:<your account>/opsctl.git # first time only git push -u origin main git push origin v1.0.0 gh run list --limit 3 gh run watch # interactively select and watch in real time gh release view v1.0.0
Problem: In March 2025, a widely used third-party action tj-actions/changed-files was compromised: attackers pointed several version tags to malicious commits, and workflows using @v45 such tags leaked secrets in logs (CVE-2025-30066). Approach: pin all third-party actions to commit SHAs and review upgrades with Dependabot; the workflow defaults to contents: read (read-only permissions). Lesson: tags are mutable references; SHAs are immutable.
Problem: The developer's local ShellCheck 0.9 reported zero warnings, but after the CI runner image was upgraded to 0.11, SC2329 (function never invoked) appeared and the build failed. Approach: Pin v0.11.0 in both CI and locally; upgrade ShellCheck as a separate PR, and merge after fixing the new warnings.
Problem: A manual tar czf opsctl.tgz . packaged the developer's etc/opsctl.conf (containing internal addresses) and the .git directory into the release package. Approach: Use only git archive <tag>, together with .gitattributes 's export-ignore; the release is produced in CI, so developer machines never produce release artifacts.
Start from “which step failed” and narrow down step by step; every conclusion comes with a local reproduction command and a fix.
Cause: recipe lines are indented with spaces instead of a Tab.
cat -A Makefile | sed -n '14,18p' # recipe lines should start with ^I sed -i 's/^ /\t/' Makefile # replace the 4 leading spaces with a Tab (check first!)
Cause: copied the test/bats directory instead of git submodule add, or .gitmodules was not committed.
git rm --cached test/bats 2>/dev/null; rm -rf test/bats git submodule add https://github.com/bats-core/bats-core.git test/bats git add .gitmodules test/bats && git commit -m "test: add bats submodule"
actions/setup-python the commit SHA a tag points to, for pinning.gh api repos/actions/setup-python/releases/latest --jq .tag_name
gh api repos/actions/setup-python/git/ref/tags/<tag> --jq '.object.sha + " " + .object.type'
# if the type is tag (annotated tag), query again: gh api repos/actions/setup-python/git/tags/<sha> --jq .object.sha
# or: git ls-remote https://github.com/actions/setup-python 'refs/tags/<tag>^{}'opsctl-1.0.0.tar.gz and .sha256, write the verification and installation commands.sha256sum -c opsctl-1.0.0.tar.gz.sha256 # macOS: shasum -a 256 -c tar -xzf opsctl-1.0.0.tar.gz && cd opsctl-1.0.0 && sh install.sh
① Add a matrix job: runs-on: [ubuntu-24.04, macos-15] (on macOS brew install bash shellcheck shfmt, and make sure bash points to the Homebrew version; check the GitHub docs for runner names); ② add a container job: container: bash:4.4 runs bash test/bats/bin/bats test/ (Alpine user space, needs apk add make git etc.), verifying minimum version and BusyBox tool compatibility; ③ add another step sh bin/opsctl help asserting exit code 3 (version guard); ④ when matrix job failures should not block anything except the release job, use fail-fast: false to see all results.
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.
| Purpose | Command / code |
|---|---|
| Trace the whole script | bash -x script.sh; bash -xv also print the raw lines |
| Local tracing (does not print set +x) | set -x; …; { set +x; } 2>/dev/null |
| Practical PS4 | PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: ' (must use single quotes) |
| With timestamps | PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE[0]##*/}:${LINENO}: ' |
| Write trace to a file | exec {fd}>>trace.log; BASH_XTRACEFD=$fd; set -x |
| Syntax check | bash -n f.sh; shfmt -d f.sh; dash -n f.sh |
| Call stack | caller 0; ${FUNCNAME[i]} ${BASH_SOURCE[i]} ${BASH_LINENO[i-1]} |
| ERR trap | set -E; trap 'echo "ERR $? at ${BASH_SOURCE[0]}:$LINENO: $BASH_COMMAND" >&2' ERR |
| DEBUG trap | set -T; trap 'echo "> $BASH_COMMAND" >&2' DEBUG |
| Inspect variables precisely | declare -p var arr |
| Code | One-line description | Fix |
|---|---|---|
| SC2086 (info) | Unquoted variable | "$var"; use an array when splitting is needed |
| SC2046 (warning) | Unquoted command substitution | find -exec … {} +,mapfile |
| SC2155 (warning) | Declaration and assignment combined, masking the exit code | local v; v=$(cmd) |
| SC2164 (warning) | cd failure unhandled | cd -- "$d" || exit |
| SC2181 (style) | Use $? for indirect checking | if ! cmd; then |
| SC2034 (warning) | Unused variable | Delete / fix the spelling / export |
| SC2045 (error) | Iterating over ls output | for f in ./* |
| SC2115 (warning) | rm -rf $d/* | rm -rf -- "${d:?}"/* |
| SC2006 (style) | Backticks | $(…) |
| SC1091 (info) | sourced file not followed | -x + # shellcheck source=… |
| SC3xxx | Non-portable constructs in POSIX sh | see M6 |
shellcheck -x -S warning bin/opsctl lib/*.sh # gate shellcheck -f gcc f.sh # editor-friendly shellcheck -f diff f.sh | git apply # auto-fix (some rules) # shellcheck disable=SC2086 # reason…… (single command) # shellcheck shell=bash (first line of a library file)
shfmt -d bin/opsctl lib test/*.bats # CI: fail if there are differences (reads .editorconfig) shfmt -l -w bin/opsctl lib # rewrite shfmt -i 2 -ci -bn f.sh # command-line arguments (ignores .editorconfig!) # .editorconfig: [*.sh] indent_style=space indent_size=2 shell_variant=bash switch_case_indent=true binary_next_line=true
Google style key points: Bash only; 2 spaces / 80 columns; main "$@"; pkg::func; local separate declaration from command-substitution assignment; [[ ]],$( ); errors to stderr; libraries .sh not executable; consider switching languages beyond 100 lines.
#!/usr/bin/env bats
bats_require_minimum_version 1.5.0
setup() {
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
STUB_BIN="$BATS_TEST_TMPDIR/bin"; mkdir -p "$STUB_BIN"; export PATH="$STUB_BIN:$PATH"
}
teardown() { :; } # always runs
@test "description" {
run --separate-stderr ./bin/opsctl nope
assert_failure 2
refute_output
assert_stderr --partial 'unknown subcommand'
}
| Assertion | Purpose |
|---|---|
assert_success / assert_failure [N] | Exit code |
assert_output 'x' / --partial / --regexp / refute_output | output exact match / contains / regex / empty |
assert_line --index 0 'x' | specific line |
assert_equal "$actual" "$expected" | two values |
assert_stderr (requires --separate-stderr) | stderr |
run -2 cmd / run ! cmd | assert the exit code directly when using run |
bats --tap / --report-formatter junit -o reports / -f regex / --jobs N | Run options |
| Slow (external command) | Fast (builtin) |
|---|---|
$(basename "$f") / $(dirname "$f") | ${f##*/} / ${f%/*} |
$(echo "$s" | tr a-z A-Z) | ${s^^} |
$(date +%F) | printf -v d '%(%F)T' -1 |
$(cat f) | $(<f) |
echo "$s" | grep -q re | [[ $s =~ re ]] |
$(expr $n + 1) / ((n++)) | ((++n)) (set -e safe) |
| Bash loop processing a large file line by line | one awk |
for f in …; do cmd "$f"; done | find … -exec cmd {} + / xargs -0 -P N |
TIMEFORMAT='%R s'; time func hyperfine -w 3 'bash a.sh' 'bash b.sh' strace -f -c -e trace=clone,clone3,execve bash a.sh
| Bash | POSIX sh |
|---|---|
[[ $a == b* ]] | case $a in b*) … ;; esac |
echo -e | printf |
source f | . ./f |
arr=(a b) | set -- a b |
cmd &> f | cmd >f 2>&1 |
function f { | f() { |
${x^^} / ${x:1:2} / ${x/a/b} | tr / cut / sed |
checkbashisms script.sh; shellcheck -s sh script.sh; dash -n script.sh
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash x.sh # the version of Bash that ships with macOS
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh x.sh # BusyBox ash
# Version guard (the style used at the opsctl entry point: the first statement is POSIX, so dash exits when it reaches it):
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)" >&2; exit 3
fi
> 100 lines or complex control flow · nested data structures · lots of JSON/YAML · floating-point/date/CSV · fine-grained error handling · concurrency with shared state · long-running services · Windows / large-scale distribution · untrusted input concatenated into commands · still not fast enough after optimization · multi-host configuration convergence (→ Ansible) · cloud resource lifecycle (→ Terraform).
make check # lint + fmt-check + test echo 1.0.0 > VERSION && git commit -am "release: 1.0.0" && git tag -a v1.0.0 -m "opsctl 1.0.0" make release # git archive + sha256sum git push origin main v1.0.0 # CI checks VERSION==tag and creates the Release # action pinned to SHA: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
A script has been circulating in the ops group chat cleanup-logs.sh: delete *.log older than N days, and compress logs older than 1 day. It runs fine on CentOS but errors on Ubuntu, and someone says it “deleted things in the home directory”. Your task: without changing the intended behavior, turn it into opsctl's cleanup subcommand, with tests, zero warnings, and ready to release.
mkdir -p ~/bashlab/final && cd ~/bashlab/final
cat > cleanup-logs.sh <<'EOF'
#!/bin/sh
# cleanup-logs.sh — delete logs older than N days and compress logs older than 1 day (legacy version: for analysis only, do not run!)
LOG_DIR=$1
DAYS=${2:-7}
cd $LOG_DIR
for f in `ls *.log`; do
age=$(( ( $(date +%s) - $(stat -c %Y $f) ) / 86400 ))
if [ $age -gt $DAYS ]; then
rm $f
elif [[ $age -ge 1 ]]; then
gzip $f
fi
done
echo "done: $(ls | wc -l) files left"
EOF
dash -n cleanup-logs.sh; checkbashisms cleanup-logs.sh; shellcheck cleanup-logs.sh. Write down at least 6 problems, and identify the one that explains “deleted things in the home directory” (hint: where does LOG_DIR go when cd is empty?).test/cleanup.bats build the directory with $BATS_TEST_TMPDIR : new files, files from 2 days ago and 10 days ago .log, and “weird-named” files (containing spaces, starting with - , which can be copied from ~/bashlab/data/files/ ). Modification times are set with touch -d '10 days ago' f (GNU; use touch -t on macOS). Expectation: files from 10 days ago are deleted, files from 2 days ago become .gz, new ones are left untouched, weird-named files are handled correctly, and when the directory argument is empty or /,$HOME it is rejected with exit code 2.lib/cmd_cleanup.sh: cmd::cleanup <dir> [--days N] [--dry-run]. Requirements: argument validation (N is a positive integer, the directory exists); reject / and $HOME; use find "$dir" -maxdepth 1 -type f -name '*.log' -mtime +"$days" -delete to handle deletion (-mtime +N meaning “number of whole days (truncated) greater than N”, consistent with the integer division semantics of the legacy script age -gt DAYS , and use tests to confirm the boundary); use -mtime +0 … -exec gzip -- {} + in batch to compress the remaining logs older than 1 day; --dry-run the dry-run option only prints; all logs go through log::*, and usage errors go to util::usage_error (2); for concurrent cleanup of the same directory, use Lesson 4's util::lock to prevent it. First deliberately do not write on line two of # opsctl-summary:, run test/bats/bin/bats -f summary test/opsctl.bats, and confirm M4's summary test fails with cmd_cleanup.sh is missing # opsctl-summary: , then add it.make check all green (ShellCheck zero warnings, no shfmt differences, all tests pass). Use OPSCTL_TRACE=1 to observe one --dry-run execution trace, and confirm that find 's arguments are all correctly quoted.find version: hyperfine -w 1 --prepare '…rebuild test directory…' 'bash old.sh d 7' 'bin/opsctl cleanup d --days 7', record the speedup ratio.find -maxdepth,-delete,stat -c,touch -d are available on GNU / BSD / BusyBox? In bash:4.4 (BusyBox tools) container, run test/cleanup.bats, and write the findings into the README's “known limitations”.VERSION, usage and CHANGELOG, then tag v1.1.0, push, and confirm that CI's release job generates opsctl-1.1.0.tar.gz and checksums.PS4 is expanded before each trace is printed; with double quotes, ${LINENO},${FUNCNAME} is expanded to a fixed value at assignment time. The first character of PS4 is repeated by indirection level: command substitution runs in a subshell, so one level is added, so it shows ++.
local v=$(cmd) The exit code of local is that of a success, masking the failure of cmd ; under set -e the script does not exit and continues with an empty value, possibly causing accidental operations. Splitting local v; v=$(cmd) from the assignment makes the assignment's exit code equal to cmd 's exit code.
run executes in a subshell and captures $status/$output/${lines[@]}, and a failing command does not fail the test — used when asserting the exit code or output. A direct call has set -e in effect, so a failure fails the test immediately, and variable changes made by functions remain in the test process — used for setup steps or when checking side effects (variables).
Prerequisites: the script calls external programs by command name, does not reset PATH, and does not hard-code absolute paths; the stub is executable and has a shebang. Limitations: builtins and shell functions cannot be replaced this way (you can redefine functions within the test to replace them); within the same process the command hash may cache the old path (hash -r); a stub only simulates the behavior you thought of, so edge cases of the real tool still need integration tests.
Check whether the runtime environment is controlled: container entry points,curl | sh installers, embedded systems, Debian maintainer scripts and other uncontrolled or minimal environments → POSIX sh, verified with shellcheck -s sh, checkbashisms, and dash/busybox containers. Ops tools, CI scripts, developer tools and other controlled environments → Bash: declare the minimum version, add a version guard, and run tests in a minimum-version container. The key is to choose one and verify it; don't write “bash that looks like sh”.
git archive <tag> contains only the tracked files of that commit, without uncommitted changes, build artifacts or local configuration, combined with export-ignore to control the content, so the results are reproducible and verifiable. An action's tag can be moved by a maintainer or an attacker (as in the 2025 tj-actions incident), while a commit SHA is immutable; pinning SHAs plus Dependabot-reviewed upgrades strikes a balance between reproducibility and secure updates.
| Topic | Verification conclusion | Sources (accessed 2026-11-17) |
|---|---|---|
| Bash version | Ubuntu 26.04 (resolute) bash 5.3-2ubuntu1; upstream 5.3 patches up to bash53-020 (5.3.20); the local test environment is Bash 5.2.37 from Git for Windows | packages.ubuntu.com;GNU FTP bash-5.3-patches |
| xtrace, PS4, BASH_XTRACEFD, caller, trap, EPOCHREALTIME | semantics follow the Bash manual; the first character of PS4 is repeated by indirection level, and the closing behavior of BASH_XTRACEFD; all trace output in this lesson was actually run on Bash 5.2.37 | GNU Bash Reference Manual |
| ShellCheck | Latest v0.11.0 (2025-08-03): adds SC2327–SC2332, SC3062; SC2002 is now off by default; SC2335 is optional; Ubuntu 26.04 apt has 0.11.0-2 | ShellCheck releases;packages.ubuntu.com |
| shfmt | Latest v3.14.1 (2026-09-06); 3.14.0 adds --detect, zsh dialect; .sh extensions parse as posix by default; EditorConfig is ignored when formatting arguments are given; old key names shell_variant/switch_case_indent are still accepted; Ubuntu 26.04 apt has 3.12.0 | mvdan/sh releases;shfmt.1.scd (v3.14.1) |
| bats-core and helper libraries | bats-core v1.14.0 (2026-07-21): run honors set -e inside functions, errors when no tests are found, adds --errexit; bats-assert v2.2.4 (assert_stderr since 2.2.0); bats-support v0.3.0; bats-file v0.4.0; Ubuntu 26.04 apt: bats 1.13.0, bats-assert 2.2.4, bats-support 0.3.0, library path /usr/lib/bats/ | bats-core releases;Writing tests;bats-assert; packages.ubuntu.com file listing |
| Google Shell Style Guide | 100-line rule, Bash only, 2 spaces/80 columns,:: package separators, main, local kept separate from command substitution,[[ ]], errors to STDERR, extension rules; the guide does not mention shfmt | shellguide.html |
| dash / POSIX | Ubuntu 26.04 and Debian 13's dash is 0.5.12; pipefail was merged into dash's mainline in 2024-04 (0.5.13); POSIX.1-2024 includes pipefail and $'…'; this lesson's dash behavior was measured on the dash bundled with Git for Windows | packages.ubuntu.com;packages.debian.org;dash.git |
| Other tool versions | devscripts 2.26.7 (checkbashisms), hyperfine 1.19.0 (apt) / 2.0.0 (upstream 2026-10-07), busybox 1.37.0, just 1.59.0 | packages.ubuntu.com; GitHub releases |
| Container image tags | bash:3.2 (3.2.57),bash:4.4 (4.4.23),bash:5.2,bash:5.3 (5.3.20),koalaman/shellcheck:v0.11.0,mvdan/shfmt:v3.14.1,bats/bats:1.14.0,busybox:1.37 all exist | Docker Hub API |
| GitHub Actions | actions/checkout Latest v7.0.1, with the tag pointing to commit 3d3c42e5aac5ba805825da76410c181273ba90b1; ShellCheck/shfmt release asset file names verified against the release pages | GitHub API (gh api repos/actions/checkout/git/ref/tags/v7.0.1) |
All videos had their titles and channels verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17:
| Video ID | Title | Channel | Used for |
|---|---|---|---|
| nvAMWPeKBrc | 10 Tips for debugging Bash Scripts (actually useful and real-world applicable) | You Suck at Programming | M1 |
| LX-APA9ugMc | Bash Debug Mode Explained | You Suck at Programming | M1 |
| Yw5qLN5bKPg | Debugging Bash Scripts: The Power of set -e, set -x, set -o, and set -u | Daily Dose of Dev | M1 |
| 28Ygo05cLmo | Linting and Improving Your Bash Scripts with ShellCheck | Nick Janetakis | M2 |
| zFDYVzU6JxA | I Learned Something New about Bash from `shellcheck` | You Suck at Programming | M2 |
| GToQwmDXUx8 | SC2086: The Bash Quoting Bug to Fix Before You Schedule a Script | FutureOps | M2 |
| lmt7rrMW_pU | Write Better Bash Scripts! Use ShellCheck and shfmt | Tom on the Internet | M3 |
| OqWacbx5rLo | Create BULLET PROOF Shell Scripts with ShellCheck and Neovim! | DevOps Toolbox | M3 |
| SB7e5qdGh9E | How to Test Docker Images and Shell Scripts (with bats-core) | Redhwan Nacef | M4, M8 |
| EHUE3i8izew | Test-Driven Development (TDD) Tutorial: Unit Testing Bash Scripts with Bats on Rocky Linux 10 | theurbanpenguin | M4 |
| sJ5LHe22IU0 | fork and exec Explained #bash | Truly Coding | M5 |
| hl3siAyoQ-w | Bash Scripting : Source and Fork your Scripts | theurbanpenguin | M5 |
| oKA2aK0-tb4 | "Overcoming the limitations of the POSIX shell command language" - Curtis Millar (LCA 2021 Online) | linux.conf.au | M6 |
| PPiPbMFKDHY | My thoughts on bash vs. Posix Compliant Shell Scripts. I am Mr. You Suck at Programming. | You Suck at Programming | M6 |
| LjGwm0Z6D24 | Shell Script Tutorial: A Look At Posix Compliant Shell Operators | Brodie Robertson | M6 |
| RQEh8XW0wLk | Python or Bash for scripting? Which is best? | Mashed | M7 |
| ASTpo4e7q9c | Python vs. Bash: Why Python CRUSHED Bash for DevOps Automation | TechTalks with Gil - SRE | M7 |
| BQrohJ3PT7I | How to use GitHub Actions | GitHub for Beginners | GitHub | M8 |
| UrODXOiqH0k | GitHub Actions: Protecting Your CI from Attackers | SANS Cloud Security | M8 |
No verified video specifically on Bash performance optimization was found for M5, so a storyboard script is provided. Small-channel videos are supplementary only; content follows this lesson and the official docs.
The “Audio” page uses the browser's built-in Web Speech API (speechSynthesis, zh-CN voice) to read the narration aloud in real time; English terms use the en-US voice. This courseware cannot embed or generate MP3 files; when audio is needed, pass the narration script to any TTS tool.
bash -n “unexpected end of file” message, which adds unclosed compound command information) have not been tested on 5.3.log.sh,util.sh appended parts,cmd_export.sh,cmd_doctor.sh,bin/opsctl,test/flaky.sh), Lesson 5 Module 8 (cmd_logs.sh,logs_report.awk, configuration keys) and Lesson 6 Module 8 (version-number sed, 8 configuration keys,cmd_health.sh,cmd_backup.sh,cmd_deploy.sh,config show key list) were extracted piece by piece to rebuild v0.3.0, then this lesson's VERSION changes were applied, and the behavior each test depends on was verified by running directly on Bash 5.2 and dash on this machine: -V, summaries of the 8 subcommands and help <name>, exit code 2 for unknown subcommands / no arguments,servers list table and tsv, invalid env 2, missing argument 2, unreadable data directory 1, precedence (--env overrides OPSCTL_ENV and no stderr by default,-v prints one DEBUG line), health exit codes 0/1/2, log text, curl arguments,OPSCTL_HEALTH_RETRIES and -r precedence, the upper bound of full-jitter waits,util::retry an off-by-one bug causing 5 calls,logs report 's gold standard and error paths,util::csv_split,log::info 's [PID] format, dash guard returning 3. *.bats The file itself was not run with bats on this machine.logs report was not modified; M7 creates a separate codes subcommand to demonstrate migration.shfmt -d run will likely produce a diff); run make fmt , then review and commit separately.ubuntu-24.04 Runner availability and preinstalled software follow the GitHub documentation./bin/sh 's implementation details (Bash 3.2 in POSIX mode, switchable to dash) come from public Apple platform materials and community documentation.strace measured values may be slightly lower.