Bash Hour 7: Testing, Debugging, Quality and Portability

Turn a script that “just runs” into a tool you can trust: track execution, run static checks, keep a consistent format, have automated tests, understand the limits of performance and portability, and know when to switch languages, finishing by releasing opsctl as v1.0
Bash 5.3 (Ubuntu 26.04)ShellCheck 0.11.0shfmt 3.14.1bats-core 1.14.0 · bats-assert 2.2.4Verified against official sources · 2026-11-17
Overall learning objectives
  • Use 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.
  • Read ShellCheck output (code, severity, fix suggestions) and fix high-frequency issues such as SC2086 / SC2046 / SC2155 / SC2164 / SC2181 with confidence; use directives and .shellcheckrc to make justified suppressions.
  • Use shfmt + EditorConfig for consistent formatting, and master the key rules of the Google Shell Style Guide (2-space indent, 80 columns,main functions,:: package separators, declaring local variables separately from their assignment, etc.).
  • Write tests with bats-core + bats-support + bats-assert: run,assert_success,assert_output,setup/teardown, a separate temporary directory for each test, and PATH injecting test doubles (stubs).
  • Find performance hotspots in Bash (fork/exec inside loops, command substitution, external commands), replace them with builtins and parameter expansion, and use time / hyperfine to measure the gains.
  • Understand the differences between POSIX sh, dash (the default /bin/sh on Debian/Ubuntu /bin/sh), the Bash 3.2 that ships with macOS, and BusyBox ash, and use checkbashisms and shellcheck -s sh to check portability.
  • Recognize the signs that it is time to switch languages, and migrate scripts step by step to Python / Go following a migration checklist.
  • Release opsctl as v1.0: 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.

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab (~/bashlab)
0Before classPreparation: testing and CI toolchainInstall ShellCheck, shfmt, bats-core and helper libraries, checkbashisms and hyperfine; get the opsctl starting codeEnvironment self-checkcheck-tools.sh
100–06Debugging: set -x, PS4, BASH_XTRACEFD and callerxtrace principles, PS4 expansion and level prefixes, trace redirection, caller call stack, bash -n, trap DEBUG/ERRxtrace step-through player (live PS4 expansion, call stack)Add OPSCTL_TRACE=1 switch
206–13Static checking: ShellCheck rules and suppressionCommon SC codes, severity levels, directives,.shellcheckrc, optional checks, output formatsCore animation: ShellCheck finds and fixes issues one by oneFix deploy-old.sh of 10 warnings
313–21Formatting and style: shfmt and style guideshfmt options and EditorConfig,-d/-l/-w, Google Shell Style Guide key rulesshfmt options live previewConfigure for opsctl .editorconfig and format
421–28Testing: bats-core, assertions and test doublesbats execution model, run, bats-assert, setup/teardown, temporary directories, PATH doublesCore animation: one bats run (setup → run → assert → teardown)Write 21 tests for opsctl (and uncover a real problem)
528–35Performance: avoiding subshells, builtins first and profilingfork/exec cost, command substitution, parameter expansion,printf -v,time/TIMEFORMAT, hyperfine,EPOCHREALTIME timingfork counter: three ways to write the same taskLog-processing function sped up 50×
635–42Portability: POSIX sh, dash, Bash 3.2 and BusyBoxbashism checklist, dash, macOS Bash 3.2, BusyBox ash, checkbashisms, version guardsPortability matrix: feature × shellRunning scripts on bash:3.2 / busybox in containers
742–50When not to use Bash: signals for migrating to Python / GoComplexity signals, data structures, error handling, concurrency, cross-platform; migration strategy“Should we switch languages?” scorerNew codes subcommand: awk and Python dual implementations, cross-checked with the same test suite
850–60opsctl v1.0: testing, CI and releaseTest suite, Makefile/justfile, GitHub Actions, VERSION, tarball and checksumsCI pipeline simulator + interactive troubleshooting treeRelease opsctl-1.0.0.tar.gz
—After classCheat sheet · Capstone labTake over a “legacy script”: add tests, fix warnings, make it portable, connect CIFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Execution tracing and call stacks✓··✓✓··✓set -x,PS4,BASH_XTRACEFD,callerM1
Static analysis and suppression strategy·✓✓··✓·✓shellcheck -x -S,.shellcheckrcM2, M8
Formatting and style conventions·✓✓····✓shfmt -d,.editorconfigM3, M8
Automated testing and doubles···✓·✓✓✓bats,run,assert_outputM4, M8
Performance profiling and optimization✓···✓·✓·time,hyperfine,strace -c -fM5
Portability (POSIX / old versions / BusyBox)·✓✓··✓✓✓checkbashisms,shellcheck -s sh,dash -nM6
Technology choice (when to switch languages)··✓·✓✓✓·—M7
CI and release·✓✓✓···✓make check,git archive,sha256sumM8, capstone lab

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

TopicWhy it is not in this lessonWhere to learn
Full GitHub Actions syntax (matrix, caching, environments, OIDC, reusable workflows)This lesson only builds one minimal working check pipelineGitHub 8 hours
Running the same checks in GitLab CI / Jenkinsthe same idea: call make checkGitLab 8 hours,Jenkins 8 hours
Configuration convergence and idempotent deployment across multiple hostsBeyond the scope of “scripts”; hand over to configuration management tools (see M7)Ansible 8 hours
Principles of strict mode, trap, locks and retriesCovered in Lesson 4; used directly in this lessonHour 4
Python / Go language itselfM7 covers only “when and how to migrate”Official tutorials for each language
Bash interview questions and production issue collectionCollected in Hour 8Hour 8

How to use this courseware

10 pages per module
Principles · diagrams · animation · commands · labs · production cases · troubleshooting · quizzes · audio · video. Suggested order: Principles → Animation → Lab → Troubleshooting. All labs run inside ~/bashlab folder.
Learning progress
A module counts as complete when the quiz score is ≥ 70% or you click “Mark this module complete”; progress is saved in this browser's localStorage (cleared on refresh if local storage is disabled).
Chinese audio
The “Audio” page reads the lecture script aloud with the browser's built-in Web Speech API (en-US); without a Chinese voice pack, read the script directly or pass it to a TTS tool.
Version notes This lesson's baseline is GNU Bash 5.3 (Ubuntu 26.04 LTS ships with 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.

Module 0 · Preparation: testing and CI toolchain (complete before class)

Install ShellCheck, shfmt, bats-core and helper libraries, get the opsctl v0.3 → v1.0 starting code, and run one self-check
Before class ≈ 10 min~/bashlab/opsctlNo root needed (except the container option)
Prerequisites
  • CompleteHour 1environment: Bash 5.x (5.3 recommended), working directory ~/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.
  • andHour 6link: at the end of the previous lesson, opsctl was at v0.3, with the directory convention 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.
  • A GitHub account and repository (M8's CI needs them); for the basics of GitHub Actions see GitHub 8 hours.

Step 1: install the tools (choose one of three)

A. Ubuntu 26.04 / Debian 13 (apt, simplest)

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).

B. macOS (Homebrew)

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.

C. Containers only (install nothing on the host)

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)
Tip In the container approach, 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.

Step 2: confirm the opsctl v0.3 interface (the “contract” the tests in this lesson are based on)

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:

InterfaceBehavior (measured on this machine)Exit code
bin/opsctl → opsctl::mainThe 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.shEX_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_add1 / 2 / 3
lib/config.shPriority: 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 noneinvalid 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 valueno valid lines / file unreadable → 1; invalid option value → 2
opsctl health [-t SEC] [-r N] [-e CODE] URLhealth::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).

Step 3: add bats and its helper libraries to the project as git submodules

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.

Step 4: environment self-check

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.
Self-check checklist
$ 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
Warning All commands in this lesson that delete files (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.

Module 1 · Debugging: set -x, PS4, BASH_XTRACEFD and caller

00:00 – 06:00 · Don't rely on scattered echo calls: let Bash tell you exactly what it ran after expansion, and in which file, line and function
6 minBash 5.3 built-in features★★★★★
Learning objectives
  • Explain that xtrace prints the expanded command, and state what +,++,+++ prefixes each mean.
  • Write a PS4 that shows ${BASH_SOURCE},${LINENO},${FUNCNAME} and explain why it must be assigned in single quotes.
  • Use BASH_XTRACEFD to separate the trace from normal stderr, use caller / FUNCNAME / BASH_LINENO to print the call stack.
  • Use bash -n for syntax checking, trap … ERR to report the failure location, and trap … DEBUG for step-through observation.
Prerequisites: the expansion order from Lesson 1, functions and the call stack from Lesson 3, and strict mode and trap from Lesson 4. Importance:★★★★★ (used whenever troubleshooting in all later modules)

What: what is xtrace

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.

ToolPurposeWhen to use
set -x / bash -x scriptPrints each command after expansion“Why is this variable empty?” “Why was this argument split into two?”
set -vPrints the raw source lines as read (unexpanded)Compare with -x to see the difference before and after expansion
PS4xtrace line prefix, expanded before every printAdds file, line, function and timestamp
BASH_XTRACEFD (Bash ≥ 4.1)Sends xtrace to a specified file descriptorToo much trace output, and you don't want to pollute stderr or logs
caller [n],FUNCNAME,BASH_SOURCE,BASH_LINENOCall stack informationPrints “who called me” in die / ERR traps
bash -n scriptParse only, don't execute (noexec)Syntax check before committing and before deploying
trap '…' DEBUGEach simple command execution before runsStep-by-step observation, simple profiling, logging $BASH_COMMAND
trap '…' ERR + set -ERuns when a command returns non-zero (and is not in a conditional context)Reports the failing command and location

Why: why not just use echo

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.

How: a practical PS4

export PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
  • Must use single quotes: PS4 is expanded each time a trace is printed. If you use double quotes,${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.
  • Optional: add ${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.

When: choose the right tool

  1. The script won't run at all (syntax error): bash -n, or shfmt -d (M3, stricter parsing).
  2. The result is wrong but there's no error: enable it only in the suspicious section set -x … set +x to avoid thousands of lines of noise.
  3. Intermittent failures that only occur in CI or production: use an environment variable switch (such as OPSCTL_TRACE=1) + BASH_XTRACEFD to write to a file for later analysis.
  4. Need to know “who called me”: in util::die or an ERR trap, print the call stack.

Comparison: Bash debugging methods

echo / printfset -x + PS4trap DEBUGbashdb (external debugger)
Requires code changesYes, addinga line or an environment variableone lineNo
Sees expanded argumentsOnly sees what you printYesVia $BASH_COMMAND (before expansion)Yes
Breakpoints / steppingNoNoCan be simulatedYes
Usable in CI / productionYesYes (watch for secret leaks)Use with care (high overhead)Rarely used
Common misconceptions① “The quotes xtrace shows are the quotes I wrote”—no, xtrace will re-quote the arguments so the output can be copied back into a shell, for example 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.

Figure 1-1: one command from source to xtrace output

Source linecp $f "$dst" Expansionparameters / command substitution / splitting / globbing Expand PS4first character × nesting level Write to xtrace fddefault 2, or BASH_XTRACEFD Execute commandbuiltin or fork/exec Source: cp $f "$dst" (f='my file.txt', dst=/tmp/out) Trace: + copy.sh:12:backup: cp my file.txt /tmp/out ← at a glance you can see $f was split into two arguments Note the order: the trace is printed before the command runs, so when a command fails, the last trace line is the “culprit”
Figure 1-1: xtrace prints after expansion and before execution; PS4 is re-expanded each time, so line numbers and function names are live

Figure 1-2: how the call stack arrays correspond

Index i FUNCNAME[i] BASH_SOURCE[i] BASH_LINENO[i] (line where it was called) 0 (current)util::dielib/util.sh63 ← line in cmd_servers.sh that calls die 1servers::listlib/cmd_servers.sh24 ← line that calls servers::list 2cmd::serverslib/cmd_servers.sh137 ← line in bin/opsctl that calls it 3opsctl::mainbin/opsctl140 ← top-level line that calls opsctl::main Rule: function FUNCNAME[i] is defined in BASH_SOURCE[i], and it was called from line BASH_LINENO[i] of BASH_SOURCE[i+1]
Figure 1-2: the three arrays line up one-to-one; 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)

xtrace step-through player: live PS4 expansion and call stack

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).

demo.sh
Call stack
stdout
stderr
xtrace (fd 2, mixed with stderr)
Choose a PS4 scheme, then click “Next step”.

Core commands and options

Command / variablePurposeNotes
bash -x script.sh argsEnable xtrace for the whole scriptno script changes needed; bash -xv also print the raw lines
set -x … set +xTrace only a section{ set +x; } 2>/dev/null the set +x itself is not printed
PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: 'Trace prefixSingle quotes! The first character is repeated per nesting level
exec {fd}>trace.log; BASH_XTRACEFD=$fdWrite trace to a fileBash ≥ 4.1; unset it or set it to an empty string to go back to stderr
caller / caller NCurrent caller / N-th level callerNo arguments: line file; with N: line function file; out of range returns non-zero
bash -n script.shSyntax checkExit code 0 means the syntax is valid; can be looped over multiple files
trap 'cmd' DEBUGRuns before each simple commandnot inherited inside functions by default; needs set -T (functrace)
trap 'cmd' ERRRuns when a command failsfunctions and subshells need set -E (errtrace)
$BASH_COMMANDText of the command currently executing (or just failed)Most useful in DEBUG/ERR traps
declare -p varPrint variables precisely (including type and arrays)More reliable than echo; shows the difference between empty and unset

1. A trace with file, line and function name

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

2. Nesting levels of command substitution

bash -c 'PS4="+ "; set -x; a=$(echo $(echo hi)); echo "$a"'
+++ echo hi
++ echo hi
+ a=hi
+ echo hi
hi

3. Write the trace to a separate file (BASH_XTRACEFD)

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).

4. ERR trap with call stack

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.

5. caller and syntax checking

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.

6. Watch each command with a DEBUG trap

bash -c 'trap '\''echo "DEBUG> $BASH_COMMAND"'\'' DEBUG; a=1; echo $a'
DEBUG> a=1
DEBUG> echo $a
1

Lab 1: add a switchable trace and call stack to opsctl (about 5 min)

Add a trace 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.

Trace to stderr, showing only the lines related to dispatch:
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.

Trace to a file, keeping stdout clean (suitable for uploading as a build artifact after a CI failure):
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.

Make 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.

Syntax-check all files:
for f in bin/opsctl lib/*.sh; do bash -n "$f" || echo "syntax error: $f"; done; echo done

Case 1: intermittent CI failure, located with a trace file

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.

Case 2: set -x wrote a password into the log

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.

Case 3: a library function fails and nobody knows who called it

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”.

Common errors and fixes

Symptom: the line numbers in PS4 are the same on every line

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 printed
syntax error: unexpected end of file

Cause: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).

$'\r': command not found

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
Symptom: after enabling BASH_XTRACEFD, the script's stderr disappeared

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).

Symptom: ERR trap does not fire inside functions

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).

Command-line exercises
1. Trace only inside function deploy , and do not print set +x this line itself.
deploy() {
  set -x
  # ... code to trace ...
  { set +x; } 2>/dev/null
}
2. Write a PS4 that shows “file:line function +millisecond timestamp”.
PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO} ${FUNCNAME[0]:-main} ${EPOCHREALTIME}: '
# EPOCHREALTIME needs Bash ≥ 5.0; the unit is seconds (the fractional part is microseconds)
Scenario analysis
A colleague says: “This backup script works fine on my machine, but in cron it emptied /var/backups.” You only have cron's email output. How would you investigate?

① 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).

Verified instructional videos

▶
10 Tips for debugging Bash Scripts (actually useful and real-world applicable) — You Suck at Programming
English · a collection of practical debugging tips, including set -x and reading trace output; the first choice for this module
▶
Bash Debug Mode Explained — You Suck at Programming
English · focuses on Bash debugging (xtrace) mode
▶
Debugging Bash Scripts: The Power of set -e, set -x, set -o, and set -u — Daily Dose of Dev
English · combining set options with debugging; can be compared with Lesson 4

Official and primary sources

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
Visual: PS4 changes from the default plus sign to “file:line:function”, and the trace scrolls line by line; lines inside command substitution show two plus signs.
Narration: PS4 is re-expanded before each print, so always use single quotes; the number of plus signs is the nesting depth.
Shot 3 · 50–75s
Visual: the trace is redirected to trace.log, and the terminal shows only clean output; the ERR trap prints a three-level call stack.
Narration: BASH_XTRACEFD separates the trace from normal output; FUNCNAME, BASH_SOURCE and BASH_LINENO together form the full call stack.
Shot 4 · 75–90s
Visual: a plaintext password appears in the log, circled in a red box.
Narration: finally, remember that set -x prints secrets verbatim; before handling secrets, turn tracing off with set +x.
or score ≥ 70% on the quiz

Module 2 · Static checking: ShellCheck rules and suppression

06:00 – 13:00 · Find unquoted variables, swallowed exit codes and a cd that keeps running after failing, before the script runs. Behind every warning is a real class of incident.
7 minShellCheck 0.11.0★★★★★
Learning objectives
  • Read ShellCheck output: location, SC code, severity (error / warning / info / style), fix suggestions and wiki links.
  • Name and fix 10 high-frequency issues: SC2086, SC2046, SC2155, SC2164, SC2181, SC2034, SC2045, SC2115, SC2006, SC1091.
  • Use directives with the correct scope (disable,source,source-path,shell,enable), and use .shellcheckrc to standardize project configuration.
  • Use -S,-f,-x and -o to integrate ShellCheck into the editor, Makefile and CI.
Prerequisites: word splitting and pathname expansion from Lesson 1, and the set -e exception rules from Lesson 4. Importance:★★★★★

What: what ShellCheck is

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 rangeMeaningExamples
SC1xxxParser issues: syntax, quoting, encodingSC1091 cannot follow a sourced file; SC1017 the file contains CR (Windows line endings)
SC2xxxGeneral semantic issues (the most)SC2086 unquoted; SC2155 declaration and assignment combined
SC3xxxNon-portable features in a sh (POSIX) dialectSC3010 [[ ]]; SC3043 local; SC3030 arrays

Severity levels

LevelMeaningTypical
errorAlmost certainly a bug or syntax errorSC2045 iterating over ls output, SC1073 parse failure
warningLikely to cause wrong behaviorSC2164 unhandled cd failure, SC2155, SC2046, SC2115, SC2034
infoCauses problems for some inputsSC2086 unquoted, SC1091
styleBetter styleSC2006 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.

Why: the real problems behind high-frequency rules

CodeProblem codeWhat happensFix
SC2086cp $f /backupf="my file.txt" is split into two arguments; f="*" the value is glob-expandedcp -- "$f" /backup
SC2046chmod 644 $(find . -name '*.conf')the command substitution result is split on whitespace and glob-expandedfind … -exec chmod 644 {} + or mapfile -d ''
SC2155local 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 triggerFirst local v, then v=$(cmd)
SC2164cd $dirafter cd fails, the script keeps running in the current directory and runs the following rmcd -- "$dir" || exit
SC2181cmd; if [ $? -ne 0 ]inserting any command in between (such as logging) overwrites $?; and under set -e, a cmd failure never reaches the ifif ! cmd; then
SC2034unused=1a misspelled variable (VERISON) or dead codedelete it, fix the spelling, or export
SC2045for f in $(ls *.log)fails when file names contain spaces or newlinesfor f in ./*.log
SC2115rm -rf $dir/*When dir is empty, it becomes rm -rf /*rm -rf -- "${dir:?}"/*
SC2006`cmd`nesting and escaping are hard to read$(cmd)
SC1091source lib/x.shShellCheck does not follow (analyze) sourced files-x + # shellcheck source=…

How: the right way to suppress (disable)

  • Fix first, suppress later. Suppress only when you can state a reason, and write the reason in a comment on the same line.
  • Keep scope minimal: put the directive directly above a command (or a function, loop or if block), and it applies only to that command or block; put it after the shebang and before the first command, and it applies to the whole file.
  • Project-level configuration Put it in .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.
  • Optional checks (off by default) are turned on with enable= ; shellcheck --list-optional lists all of them. Since 0.11.0, SC2002 (useless cat) is an optional check that is off by default.

When: where to run it

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.

Comparison with similar tools

ShellCheckbash -nshfmtcheckbashisms
Finds syntax errorsYesYesYes (stricter)Partially
Finds semantic traps (quoting, exit codes)YesNoNoNo
PortabilityYes (SC3xxx)NoDialect-aware parsingYes (specialized)
Rewrites codePartially auto-fixable (-f diff)NoFormattingNo
Common misconceptions① “No ShellCheck errors means it is safe”—it cannot see runtime data and does not understand business logic; tests are still needed (M4). ② “SC2086 is just a style issue”—it is one of the most common sources of real bugs in shell scripts, especially when file names contain spaces. ③ “Adding # 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.

Figure 2-1: ShellCheck's analysis pipeline

Script + rcshebang / shell= Determine dialectbash / sh / dash / ksh Parse to ASTSC1xxx checked here Run rulesData flow · SC2xxx/SC3xxx Filter → outputDirectives · -e · -S · -f format -x / external-sources=trueFollow sourced files, merge variable and function definitions Exit codes: 0 no issues · 1 issues found · 2 a file could not be processed · 3/4 argument or option error — the CI gate relies on this exit code
Figure 2-1: ShellCheck determines the dialect before parsing; the same code gets different warnings under the bash and sh dialects

Figure 2-2: the scope of directives

#!/usr/bin/env bash # shellcheck disable=SC2034 ← before the first command: applies to the whole file set -euo pipefail # shellcheck disable=SC2086 # reason: $opts needs to be split on spaces rsync $opts "$src" "$dst" ← applies only to this command # shellcheck source=lib/log.sh source "${HOME_DIR}/lib/log.sh" ← tells ShellCheck which file the dynamic path refers to f() { … } ← a directive placed before a function definition applies to the whole function body .shellcheckrc (project level) external-sources=true source-path=SCRIPTDIR enable=require-variable-braces enable=deprecate-which # disable=SC1091 (not recommended globally) Searched upward from the file's directory --norc ignores it
Figure 2-2: scope from smallest to largest: single command → block/function → whole file → project .shellcheckrc; the smaller the scope, the safer

Core animation: ShellCheck finds and fixes issues one by one

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.

deploy-old.sh
ShellCheck output
Click “Next step” to run shellcheck deploy-old.sh.

Core commands and options

CommandPurposeNotes
shellcheck script.shCheck (default tty format)Exit code 0 = no issues, 1 = issues found
shellcheck -x bin/opsctl lib/*.shFollow sourced filesequivalent to external-sources=true
-S error|warning|info|styleMinimum severity levelCommon in CI gates -S warning Starting point
-e SC2086,SC2034 / -i SC2086Exclude / include only certain codesCommand-line level, broader than directives; use with care
-s sh|bash|dash|ksh|busyboxSpecify dialectFor library files without a shebang, use # shellcheck shell=bash is better
-f tty|gcc|json1|checkstyle|diff|quietOutput formatgcc good for editor navigation; checkstyle good for CI reports; diff auto-fixable
-o all / --list-optionalEnable / list optional checkse.g. require-variable-braces,check-extra-masked-returns
-P SCRIPTDIRsource search pathequivalent directive source-path=
--norcignore .shellcheckrcInvestigate “why local and CI results differ”
shellcheck -W 0 --wiki-link-count=0do not print wiki linksCompact output

1. Check the negative example

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.

2. Fixed version

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

3. Serious issues only, auto-fix, machine-readable output

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.

4. Directives and .shellcheckrc

# 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"

Lab 2: fix deploy-old.sh to zero warnings (about 6 min)

Baseline count (grouped by code and level):
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.

Fix in order of severity, from high to low:: first error (SC2045), then warning (SC2164, SC2115, SC2155, SC2046, SC2034), finally info/style. After fixing each category, rerun shellcheck -S warning deploy-old.sh to confirm the count has dropped.
Verify the real harm of SC2155 (why it is a warning rather than style):
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).

Verify the real harm of SC2086 (safe demonstration inside ~/bashlab):
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'
Run on opsctl with a .shellcheckrc added: create it as described in section 4 of the Commands page: .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.

Case 1: an empty variable deleted an entire directory

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.

Case 2: tighten the CI gate step by step

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.

Case 3: suppressions need review

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.

Common errors and fixes

SC1091 (info): Not following: lib/log.sh was not specified as input (see shellcheck -x).

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).

SC2154 (warning): var is referenced but not assigned.

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.

SC2148 (error): Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.

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
SC1017 (error): Literal carriage return. Run script through tr -d '\r' .

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
Symptom: local ShellCheck reports zero warnings, but CI fails

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.

Command-line exercises
1. Check only the .sh files modified on the current branch relative to main, and report only warning and above.
git diff --name-only --diff-filter=d origin/main -- '*.sh' | xargs -r shellcheck -x -S warning
2. Fix SC2155 and SC2164 below: local out=$(cd $dir; ls)
local out
out=$(cd -- "$dir" && ls) || return
# Better approach: don't parse ls; use an array instead: files=("$dir"/*)
Scenario analysis
The team wants to globally disable .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.

Verified instructional videos

▶
Linting and Improving Your Bash Scripts with ShellCheck — Nick Janetakis
English · a real-script demonstration of the obvious and hidden problems ShellCheck finds; the first choice for this module
▶
I Learned Something New about Bash from `shellcheck` — You Suck at Programming
English · starts from one warning and explains the Bash semantics behind it
▶
SC2086: The Bash Quoting Bug to Fix Before You Schedule a Script — FutureOps
English · focuses on SC2086 (unquoted variables); a small channel, so the content follows this lesson and the wiki

Official and primary sources

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: a 13-line deployment script; after running shellcheck, 13 warnings scroll out, colored by severity.
Narration: ShellCheck does not run your script; it reads the syntax tree and tells you where things will go wrong before they do.
Shot 2 · 20–50s
Visual: an animation of rm running in the wrong directory after cd fails; a red warning for rm -rf slash-star when a variable is empty.
Narration: SC2164 and SC2115 look like just two warnings, but behind them are two kinds of real data-deletion incidents.
Shot 3 · 50–75s
Visual: fixing line by line; the warning count drops from 13 to 0.
Narration: fix errors first, then warnings, and finally info and style; rerun after each category.
Shot 4 · 75–90s
Visual: a single-line disable directive followed by a reason comment, next to the project's .shellcheckrc.
Narration: when suppression is really needed, keep the scope minimal and state the reason clearly.
or score ≥ 70% on the quiz

Module 3 · Formatting and style: shfmt and the style guide

13:00 – 21:00 · Leave formatting to the machine so reviews only discuss logic: shfmt + EditorConfig for consistent formatting, Google Shell Style Guide for consistent conventions
8 minshfmt 3.14.1 (apt 3.12.0)★★★★☆
Learning objectives
  • Use shfmt -d (check),-l (list),-w (rewrite) to format scripts, and understand the effects of -i,-ci,-bn,-sr,-fn, and -s .
  • Use .editorconfig to save the shfmt configuration, and know that “once formatting arguments are given on the command line, EditorConfig is completely ignored”.
  • Understand how shfmt determines the dialect (extension, shebang), and avoid .sh library files being parsed as POSIX.
  • Remember the key rules of the Google Shell Style Guide and apply them to opsctl.
Prerequisites: ShellCheck from M2. Importance:★★★★☆

What: what shfmt is

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).

OptionEditorConfig keyEffect
-i Nindent_style / indent_size0 = Tab (default), N > 0 = N spaces
-ciswitch_case_indent (new spelling case_indent)case branches are indented one level more than the case keyword
-bnbinary_next_linewhen wrapping lines, move &&,||,| to the start of the next line
-srspace_redirectsadd a space after redirection operators: > file
-fnfunction_next_linefunction's { goes on the next line
-kpkeep_paddingkeep spaces used for alignment
-ssimplifysimplify code (for example remove the redundant $(( $a )) in $)
-ln bash|posix|mksh|bats|zshshell_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.

Why: why format automatically

  • Reviews no longer argue about indentation and spacing, and the diff contains only real logic changes.
  • shfmt -d In CI it serves as a “format gate” and a “strict syntax check”.
  • Consistent structure (such as case-branch indentation and pipeline line-break positions) makes scripts easier to read and grep.

How: how the dialect is determined (an important pitfall)

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.

Key rules of the Google Shell Style Guide

RuleKey points from the originalHow it applies in opsctl
When to use ShellScripts over 100 lines, or with unintuitive control flow, should move to a structured language as soon as possibleM7 migration signals
Use Bash only“Bash is the only shell scripting language permitted for executables.”#!/usr/bin/env bash
Indentation and line width2 spaces, no tabs; 80 columns maximumindent_size = 2
Pipeline line breaksKeep on one line if it fits; otherwise one stage per line, with the pipe at the start of the line and 2-space indentationbinary_next_line = true
Function naminglowercase with underscores; library functions may use :: as a package separatorlog::info,util::die,cmd::servers
main functionscripts containing at least one other function must have a main, and the last line main "$@"bin/opsctl
Local variablesdeclare with local; when the value comes from a command substitution, declaration and assignment must be separatecorresponds to SC2155
Testing[[ … ]] prefer [ … ] over testconsistent within the library [[ ]] (the version guard at the entry point is an exception; see M6)
Command substitutionuse $(command), not backtickscorresponds to SC2006
Error outputall error messages are written to STDERRlib/log.sh all >&2
File extensionsexecutables use .sh or no extension; libraries must use .sh and must not be executablebin/opsctl no extension,lib/*.sh permissions 644
Constantsall uppercase,readonly or declare -rreadonly OPSCTL_HOME
Toolsrecommended: use ShellCheck on all scriptsM2, M8
Otheravoid eval; use arrays to hold argument lists; read command output with process substitution or readarray rather than piping into whileLessons 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).

Common misconceptions① “shfmt fixes bugs”—it only changes formatting (-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.

Figure 3-1: how shfmt works and where its configuration comes from

Source fileextension + shebang choose dialect.sh ⇒ posix (special case) Parse to ASTsyntax errors are reported here Printper print options -d / -l / -wdiff · list · rewrite command-line arguments (-i/-ci/-ln…)once present → EditorConfig is completely ignored .editorconfig (searched upward)used when there are no arguments -d outputs a diff and exits non-zero when formatting differs — this is CI's format gate
Figure 3-1: configure with either command-line arguments or EditorConfig; they are not merged

Figure 3-2: opsctl's style skeleton

#!/usr/bin/env bash ← Bash only set -Eeuo pipefail readonly OPSCTL_HOME ← constants uppercase + readonly source "${OPSCTL_HOME}/lib/log.sh" usage() { … } ← lowercase + underscores main() { ← must have main local cmd=${1:-help} ← 2-space indent } … main "$@" ← last line # shellcheck shell=bash ← lib/*.sh: no shebang, not executable log::info() { … } ← package name::function name util::die() { local msg=$1 code=${2:-1} log::error "${msg}" ← errors go to stderr exit "${code}" } local out; out=$(cmd) ← declaration and assignment separated
Figure 3-2: conventions for the entry point (left) and the library (right), matching the Google Shell Style Guide

shfmt options live preview

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.

Input messy.sh
shfmt messy.sh

Core commands and options

CommandPurposeNotes
shfmt file.shPrint the formatted result to stdoutdoes not modify files
shfmt -d .Print a diff and exit non-zero if the formatting differsCI 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 placecommit first, then rewrite, for easy rollback
shfmt -f .List only the Shell files in a directoryidentified by extension and shebang; new in 3.14 --detect exec|all
shfmt -i 2 -ci -bnmanual's example combinationclose to Google style
shfmt -ln bash / -pforce dialect / POSIXmakes EditorConfig ineffective
shfmt --filename=x.sh < x.shmake EditorConfig apply when reading from stdinfor editor integration

1. Observe default formatting and common options

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
}

2. Write .editorconfig for opsctl

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.

3. Strict syntax check with shfmt

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.

Lab 3: unify the style of opsctl (about 7 min)

First commit the current state (formatting should be a separate commit):
cd ~/bashlab/opsctl
git add -A && git commit -qm "chore: before shfmt" || true
Create (see section 2 of the Commands page), then check:
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).

Rewrite and review:
shfmt -l -w bin/opsctl lib
git diff --stat
git diff bin/opsctl | head -n 20
Check against the style checklist:
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.

Commit the formatting and let blame ignore it:
git commit -qam "style: shfmt"
git rev-parse HEAD >> .git-blame-ignore-revs
git config blame.ignoreRevsFile .git-blame-ignore-revs

Case 1: the format war ended with an .editorconfig

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.

Case 2: .sh libraries were parsed as POSIX

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.

Case 3: using the style guide's 100-line rule for a technical decision

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.

Common errors and fixes

lib/log.sh:…: … is a bash feature; tried parsing as posix

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)
Symptom: I changed .editorconfig, but shfmt output did not change

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
Symptom: shfmt -d always fails in the Makefile, but locally shfmt -w leaves things looking the same

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.

Symptom: shfmt “scrambled” my aligned comments and assignments

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).

Command-line exercises
1. List the Shell files in the repository that are not correctly formatted, but skip the vendor/ directory.
printf '[vendor/**]\nignore = true\n' >> .editorconfig
shfmt -l .
2. Verify the syntax of all scripts with one command (without modifying files); return non-zero if any one fails.
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
Scenario analysis
A new colleague asks: “Since we have shfmt, do we still need the style guide?”

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).

Verified instructional videos

▶
Write Better Bash Scripts! Use ShellCheck and shfmt — Tom on the Internet
English · demonstrates everyday use of ShellCheck and shfmt together; the first choice for this module
▶
Create BULLET PROOF Shell Scripts with ShellCheck and Neovim! — DevOps Toolbox
English · editor integration: check on save (a complement to M2/M3)

Official and primary sources

Video storyboard script (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: a PR diff in which 80% of the red and green lines are only indentation changes.
Narration: formatting issues should not take up review time; hand them to a machine.
Shot 2 · 20–45s
Visual: switching -i 2, -ci, -bn, with the output on the right changing live.
Narration: shfmt prints only after parsing the full syntax tree, so formatting does not change semantics.
Shot 3 · 45–75s
Visual: the .editorconfig file,shell_variant = bash with one line highlighted; in CI, shfmt -d failing shows the diff.
Narration: remember two traps: a .sh file is parsed as POSIX by default; once arguments are given on the command line, EditorConfig no longer applies.
or score ≥ 70% on the quiz

Module 4 · Testing: bats-core, assertions and test doubles

21:00 – 28:00 · Write real automated tests for shell scripts: each test runs in its own process with its own temporary directory, and fake commands on PATH isolate the network and external systems
7 minbats-core 1.14.0 · bats-assert 2.2.4 · bats-support 0.3.0★★★★★
Learning objectives
  • State the bats execution model: preprocessing @test → one separate process per test → setup → test body → teardown, and the timing of setup_file/teardown_file .
  • Use correctly run ($status,$output,${lines[@]},-N,!,--separate-stderr) and bats-assert assertions.
  • Use $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.
  • Avoid common traps: run cmd | grep, set -e aborting a test when there is no run, and expected strings starting with -- .
Prerequisites: functions and source from Lesson 3, exit codes and set -e from Lesson 4. Importance:★★★★★

What: what bats-core is

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).

ComponentPurposeVersion in this lesson
bats-coreTest runner: discovers tests, runs them in isolation, outputs results (pretty / TAP / JUnit)1.14.0 (2026-07-21)
bats-supportHelper library: unified failure message format (bats-assert depends on it and must be loaded first)0.3.0
bats-assertAssertions: 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

Execution model (why tests do not affect each other)

  1. Preprocessing: bats rewrites .bats blocks in each @test "…" { file into ordinary Bash functions and registers the list of tests.
  2. Each .bats file is one execution process: first runs 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.
  3. Each test runs in its own child process: setup → test function → teardown. Variables changed in the test,cd,export PATH all stay out of the next test.
  4. teardown always runs, even if the test fails or is 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.
  5. Each test has a unique $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: turn a “command that may fail” into data you can assert on

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.

Why: do shell scripts need tests too?

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).

How: test doubles (stubs) — PATH injection

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.

When: what to test and what not to test

Suitable for batsNot suitable / find another way
CLI contract: usage, exit codes, stdout/stderr separation, output formatEnd-to-end behavior against real cloud APIs (use integration tests in a staging environment)
Argument parsing and error pathsOperations 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)

Comparison: shell testing frameworks

bats-coreshunit2ShellSpec
Style@test blocks + plain BashxUnit functions (testXxx)BDD DSL (Describe/It)
Target shellBashPOSIX sh familymany POSIX shells
EcosystemMost active; support/assert/file helper libraries; packages available on Ubuntu/HomebrewEstablished, lightweightBuilt-in mocks, coverage (with kcov)
Common misconceptions① “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.

Figure 4-1: bats process structure and lifecycle

bats test/Discover *.bats · preprocess file process opsctl.batssetup_file … teardown_file test process #1 (independent) test process #2 (independent) formatterpretty · tap · junit setup test bodyset -e in effect run cmdsubshell · capture assertionfailure = immediate abort teardownalways runs an assertion failure also jumps to teardown $status · $output · ${lines[@]} · $stderr Each test: separate process + separate $BATS_TEST_TMPDIR → no sharing of variables, directories or PATH changes between tests
Figure 4-1: bats hierarchy: runner → file process → independent process per test; teardown always runs

Figure 4-2: PATH injection of test doubles

opsctl health URLcall curl … PATH lookup (left to right) 1. $BATS_TEST_TMPDIR/bin/curl ← match (fake command) 2. /usr/local/bin 3. /usr/bin/curl (the real one, never called) fake curlappend "$*" → curl.callsoutput 200 · exit 0/7 assert: assert_failure 1 · wc -l < curl.calls == 3 · arguments include --max-time 5Control inputs (exit codes) + observe interactions (call records) = you can test retry logic without a network connection
Figure 4-2: a test double takes effect only in this test's process and is deleted with the temp directory when the test ends

Core animation: one bats run (setup → run → assert → teardown)

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.

test/health.bats
Process tree
Variables captured by run
Choose a scenario to start.
$ test/bats/bin/bats test/health.bats

Core commands and API

Command / functionPurposeNotes
bats test/Run all .bats in a directoryFrom 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 junitTAP / JUnit output--report-formatter junit -o reports/ keeps terminal output too
bats --jobs 4Parallelrequires GNU parallel
bats --print-output-on-failureAutomatically print $output on failurerecommended in CI
bats -x / --tracePrint the commands executed within a testfor debugging the tests themselves
bats --no-tempdir-cleanupKeep temporary directoriesfor troubleshooting failing tests
run [-N|!] [--separate-stderr] cmdRun and capturerequires bats_require_minimum_version 1.5.0
assert_success / assert_failure [N]check $statuson failure, print status and output
assert_output [-p|-e] 'x' / refute_outputexact match / contains / regex / no outputwhen the expected value starts with - , use -- as a separator
assert_line [--index N] [-p] 'x'a particular line or any lineempty lines are removed from lines
assert_equal actual expectedtwo values are equalMind the argument order: actual value first,
assert_stderr / refute_stderrthen the expected value $stderrbats-assert ≥ 2.2.0; with --separate-stderr
load 'path' / bats_load_library nameto load helper files / load libraries via BATS_LIB_PATHlibraries installed by apt are in /usr/lib/bats/
skip "reason"skip the testcan be placed inside an if to skip conditionally
echo "# msg" >&3print debug information in a testwriting to fd 3 makes it appear in the report

1. Shared test helper file

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.

2. A complete test file: test/health.bats

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.

3. TAP and JUnit output (for CI)

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

4. Pipe traps and the correct approach

# 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

Lab 4: write a test suite for opsctl (about 7 min)

Preparation: complete step 2 of the Preparation page (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).
Write CLI contract tests 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 library functions directly 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.

Write a “gold standard” test for the Lesson 5 report 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.

Deliberately introduce a bug and see the test catch it: in 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.

(Optional) use Lesson 1's full dataset: 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.

Keep the scene for troubleshooting: 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.

Case 1: regression in retry logic

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.

Case 2: stdout contract polluted by logs

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.

Case 3: the test suite fails randomly on CI

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.

Common errors and fixes

bats: command not found / test/bats/bin/bats: No such file or directory

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
bats_load_safe: Could not find '…/test_helper/bats-support/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
BW02: Using flags on `run` requires at least BATS_VERSION=1.5.0. Use `bats_require_minimum_version 1.5.0` to fix this message.

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).

assert_output: Unknown option --env (the expected string starts with --)

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'
Symptom: asserting stderr always fails ($stderr is empty)

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 .

Symptom: the stub did not take effect, and the real curl was called

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
Command-line exercises
1. Write a test: with the fixture data,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'
}
2. Write a test: when 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 curl
Scenario analysis
deploy 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 "$@").

Verified instructional videos

▶
How to Test Docker Images and Shell Scripts (with bats-core) — Redhwan Nacef
English · testing shell scripts and container images with bats-core; the first choice for this module
▶
Test-Driven Development (TDD) Tutorial: Unit Testing Bash Scripts with Bats on Rocky Linux 10 — theurbanpenguin
English · writing bats tests for Bash scripts at a TDD pace

Official and primary sources

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: one @test block is preprocessed into an ordinary function, and three independent process boxes appear side by side.
Narration: bats turns each test into a function and runs it in its own process, so tests do not interfere with each other.
Shot 2 · 20–50s
Visual: setup inserts the stub directory at the front of PATH; opsctl calls curl, an arrow veers into the fake curl, and the call record file grows line by line.
Narration: you can test retry logic without a network connection: the fake command decides what to return, and records how many times it was called.
Shot 3 · 50–75s
Visual: run puts the exit code and output into the two boxes status and output; three assertions tick off in turn; switching to the buggy version turns the third assertion red, and the arrow jumps straight to teardown.
Narration: a failed assertion ends the test body immediately, but teardown always runs.
Shot 4 · 75–90s
Visual: the terminal shows twenty-eight check marks and 0 failures.
Narration: contract tests, error-path tests and library unit tests together form the script's safety net.
or score ≥ 70% on the quiz

Module 5 · Performance: avoiding subshells, builtins first and profiling

28:00 – 35:00 · Bash is slow almost never because “the interpreter is slow”, but because every line in a loop forks and execs external commands
7 minBash 5.3 · hyperfine 2.0.0 (apt 1.19.0)★★★★☆
Learning objectives
  • Explain why $(…), pipelines and external commands are costly inside loops (fork + exec + wait), and count how many processes each iteration of a piece of code creates.
  • Replace external commands with builtins such as parameter expansion,[[ =~ ]],printf -v,$(<file),mapfile,read and so on.
  • Know when the whole loop should be handed to awk / sort / one external program in a single call.
  • Use time/TIMEFORMAT,EPOCHREALTIME, hyperfine,strace -c -f to measure performance rather than guessing.
Prerequisites: fork/exec and builtins from Lesson 1; parameter expansion and subshells from Lesson 2. Importance:★★★★☆

What: where Bash spends its time

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 writingProcesses per iterationAlternative (0 processes)
b=$(basename "$f")2 (subshell + basename)b=${f##*/}
d=$(dirname "$f")2d=${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)3up=${s^^} (Bash ≥ 4)
n=$(expr $n + 1)2((++n))
ts=$(date +%F)2printf -v ts '%(%F)T' -1 (Bash ≥ 4.2)
c=$(cat file)2c=$(<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 variableswhile read … done < <(cmd) or shopt -s lastpipe

Why: a real order of magnitude

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.

How: three optimization principles

  1. Move external commands out of the loop: use builtins when you can (parameter expansion,[[ ]],(( )),printf -v,read,mapfile).
  2. Hand the loop to a specialized tool: line-by-line text processing is the home turf of awk, sort, uniq and join — one awk process handles a million lines far faster than a Bash loop running a million times (Lesson 5).
  3. Batch external command calls: 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.

When: when optimization is worth it

  • A script that runs once in 2 seconds, once a day: not worth it; readability comes first.
  • Running every minute in cron, processing GB-scale logs, or being invoked thousands of times in CI: worth it.
  • Measure first (time, hyperfine), then optimize the hotspots; after optimizing, use tests (M4) to make sure the results stay the same.
  • If it is still not fast enough after optimizing, or needs complex data structures — this is the “switch languages” signal M7 describes.

Comparison: timing and profiling tools

ToolWhat it measuresAdvantagesNotes
time (keyword)real/user/sys for a pipelinebuiltin; can time functions and pipelines; TIMEFORMAT customsingle measurement, large variance
/usr/bin/time -vmaximum memory and context switches of external programsresource detailscannot time shell functions
EPOCHREALTIMEelapsed time between any two points in the scriptno fork, microsecond resolution (Bash ≥ 5.0)the value is a string with a decimal point; strip the decimal point before arithmetic
hyperfinestatistics across multiple runs (mean ± standard deviation)warm-up, comparing multiple commands, exporting Markdown/JSONmeasures the whole command (including shell startup)
strace -c -fnumber of system calls (clone/execve)counts fork calls directlysignificant overhead; only for diagnosis
xtrace with timestamps (PS4)per-line timinglocate the slow line (M1)high overhead, results skewed high
Common misconceptions① “[ 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)).

Figure 5-1: the processes behind one command substitution

code=$(echo "$line" | cut -d'"' -f3 | cut -d' ' -f2) Bash (parent)pipe() · fork() · wait() subshell ①command substitution ② subshell: echo (builtin) ③ fork + execve cut ④ fork + execve cut alternative: 0 processesrest=${line#*\" }code=${rest%% *} 4 processes per line × 1000 lines = 4000 forks (2000 of them also execve) Linux: about 1 ms/call → seconds; Git Bash: about 20 ms/call → more than a minute
Figure 5-1: a seemingly simple command substitution creates 4 processes per iteration (the exact number of subshells varies slightly with Bash version optimizations)

Figure 5-2: optimization decisions

Measure firsttime · hyperfine external commands in the loop?→ replace with builtins / parameter expansion processing a large file line by line?→ hand the whole thing to awk/sort N calls to the same command?→ -exec {} + / xargs mainly I/O wait?→ xargs -P for parallelism still not enough?→ switch languages (M7)
Figure 5-2: re-measure after each optimization step; use tests to make sure results do not change

fork counter: three ways to do the same task

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.


      
Choose a method, then click “Run”.

Core commands

CommandPurposeNotes
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.shcount clone/execve callsneeds strace; for diagnosis only
t0=$EPOCHREALTIMEmicrosecond 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 variableinstead of var=$(printf …)
mapfile -t arr < fileread the whole file into an arrayinstead of line by line arr+=("$(…)"); Bash ≥ 4.0
[[ $s =~ re ]]; ${BASH_REMATCH[1]}regex matching and captureinstead of echo | grep | sed

1. Measured results for the three approaches

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.

2. Count processes with strace, and use hyperfine for statistics

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”.

3. Timing inside a script with EPOCHREALTIME

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]/}.

4. Quick reference for common substitutions

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"

Lab 5: speed up the log report of opsctl (about 6 min)

Measure the baseline:
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.

Find hotspots: enable a timestamped trace and count which line is executed most often:
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:function
Count processes: strace -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.
Rewrite the hotspots: in the loop, replace $(…),echo | cut,date with parameter expansion,[[ =~ ]],printf -v; or replace the whole loop with one awk program.
Prove the results are unchanged (cross-check):
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.

Case 1: a cron job went from 40 minutes to 20 seconds

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).

Case 2: testing on a Windows dev machine was painfully slow

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).

Case 3: batch calls instead of one-by-one calls

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 (+).

Common errors and fixes

Symptom: the script exits mysteriously while counting under set -e (((n++)) returns 1)

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
Symptom: after optimization, the variable accumulated in a while loop is 0 outside the loop

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)
bash: fork: retry: Resource temporarily unavailable

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 &
printf: `(': invalid format character (or %(…)T is printed as-is)

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).

Command-line exercises
1. Without using any external commands, split /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"
2. Compare the time taken by 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 s
Scenario analysis
A script goes through 50,000 hosts one at a time with ssh 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).

Verified instructional videos

▶
fork and exec Explained #bash — Truly Coding
English short video · the concept of fork and exec, the foundation of this module's cost model; a small channel, so the content follows this lesson
▶
Bash Scripting : Source and Fork your Scripts — theurbanpenguin
English · the difference between source (current shell) and fork (child process) when running a script

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.

Official and primary sources

Video storyboard script (about 80 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: one line $(echo | cut | cut), with four process boxes popping up on screen on each loop iteration while the counter climbs quickly.
Narration: Bash is slow usually not because the interpreter is slow, but because every line in the loop creates new processes.
Shot 2 · 20–50s
Visual: the same logic with parameter expansion, and the process boxes disappear; then replaced with a single awk, leaving just one box. Three timing bars: 75 seconds, 0.19 seconds, 0.04 seconds.
Narration: builtins instead of external commands, or handing the whole loop to awk, give exactly the same results at speeds hundreds of times faster.
Shot 3 · 50–80s
Visual: hyperfine prints mean and standard deviation; strace counts execve calls.
Narration: measure before optimizing, and use tests to keep results unchanged. If it is still not fast enough after optimizing as far as possible, that is the signal to switch languages.
or score ≥ 70% on the quiz

Module 6 · Portability: POSIX sh, dash, Bash 3.2 on macOS and BusyBox

35:00 – 42:00 · Why does a script that “works on my machine” break on Debian's /bin/sh, a colleague's Mac, or an Alpine container?
7 mindash 0.5.12 · Bash 3.2.57 · BusyBox 1.37.0★★★★☆
Learning objectives
  • Distinguish the POSIX sh specification from concrete implementations: dash (the /bin/sh), Bash's POSIX mode, BusyBox ash, and the Bash 3.2 that ships with macOS.
  • List the most common bashisms and their POSIX equivalents; list the 4.x/5.x features missing from Bash 3.2 (associative arrays, mapfile, case conversion, etc.).
  • Verify portability with checkbashisms,shellcheck -s sh,dash -n and containers (bash:3.2,busybox:1.37).
  • Make an explicit choice: either write real POSIX sh, or declare “requires Bash ≥ X” and add a version guard — don't stay in between.
Prerequisites: shebang and expansion from Lesson 1; arrays from Lesson 2. Importance:★★★★☆

What: who is /bin/sh

System/bin/sh actually isbashNotes
Ubuntu 26.04 / Debian 13dash 0.5.125.3 (Ubuntu)dash starts fast and closely follows POSIX; system scripts (such as init scripts and maintainer scripts) use sh
RHEL / Fedora / Rockybash (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 imagesBusyBox ashnot present by default (needs apk add bash)Official bash:* images are also based on Alpine: user-space tools are BusyBox
macOSprovided 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 zshnewer Bash installed via Homebrew is in /opt/homebrew/bin/bash
Git for Windowsbash (MSYS2)5.2.xone of the test environments used in this lesson

Common bashisms and POSIX equivalents

Bash formdash's reaction (measured)POSIX form
[[ $a == b* ]][[: not foundcase $a in b*) … ;; esac
arr=(a b)Syntax error: "(" unexpectedset -- a b (positional parameters) or a newline-separated string
function f { … }Syntax error: "}" unexpectedf() { … }
source filesource: not found. ./file
echo -e "a\tb"output -e a<Tab>bprintf 'a\tb\n'
${x^^},${x:1:2},${x/l/L}Bad substitutiontr,cut,sed, or ${x#…}/${x%…}
$((2**10))arithmetic expression: expecting primaryloop multiplication, or awk
cat <<< hiSyntax error: redirection unexpectedprintf '%s\n' hi | cat
cmd &> fsilently parsed as cmd & + > f: run in the background and empty fcmd >f 2>&1
echo {1..3} / $RANDOMprinted as-is {1..3} / empty stringseq 1 3 / awk 'BEGIN{srand();print int(rand()*32768)}'
set -o pipefailset: 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=1fine (dash and ash both support it)strict POSIX does not define local, but in practice almost all sh implementations support it

common features missing from macOS Bash 3.2

FeatureIntroduced inBehavior on 3.2
associative arrays declare -A4.0declare: -A: invalid option
mapfile / readarray4.0mapfile: command not found
${x,,} / ${x^^}4.0bad substitution
|&,&>>,globstar (**),coproc,;&/;;&,$BASHPID4.0syntax error or invalid
{fd}>file automatic fd allocation,BASH_XTRACEFD4.1invalid
printf '%(fmt)T',[[ -v var ]],lastpipe4.2invalid
declare -n (nameref),wait -n, negative subscripts ${a[-1]}4.3invalid
${x@Q},local -,inherit_errexit; set -u under "${empty[@]}" no longer reports unbound4.4on 3.2, an empty array + set -u errors out directly
EPOCHSECONDS / EPOCHREALTIME5.0empty
${ cmd; },${| cmd; },GLOBSORT5.3syntax 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 ash

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 [[ ]] .

Why / When: two routes, choose one

Route A: POSIX shRoute B: explicitly require Bash ≥ X
shebang#!/bin/sh#!/usr/bin/env bash
Suitable forcontainer entrypoints, install scripts (curl | sh), embedded systems, initramfs, Debian package maintainer scriptsops tools, CI scripts, developer tools (such as opsctl)
checkshellcheck -s sh,checkbashisms, run tests in dash and busyboxversion guard + run tests on the minimum version (such as bash:4.4 image)
Costno arrays,[[ ]],local conveniences beyondmacOS users need to install a newer Bash
Common misconceptions① “I used #!/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.

Figure 6-1: the shell family and compatibility scope

Bash 5.3 features (${ cmd; }, GLOBSORT …) Bash 4.x features (associative arrays, mapfile, ${x,,}, nameref …) — macOS 3.2 stops here ↓ Bash 3.2 / common extensions ([[ ]], arrays, ${x:1:2}, <<<, source, $RANDOM, {1..3}) POSIX sh (+ local, nearly universal)common subset of dash · posh · bash --posixcase, [ ], ${x#…}, $(( )), printf, . BusyBox ashPOSIX + some bash extensionsno arrays · reduced tool options The further inward you go, the more portable; before writing a script, decide which ring it sits in, and verify with the matching tools and containers
Figure 6-1: portability is a question of feature subsets; the target environment decides which ring you can use

Figure 6-2: same script, different interpreters

opsctl#!/usr/bin/env bash ./opsctl → env looks up bash in PATH sh opsctl → dash (ignores the shebang) /bin/bash opsctl (macOS) → 3.2 Bash 5.3: runs normally guard: please run with bash, not sh → 3 version guard: exit 3 (instead of a cryptic error)
Figure 6-2: the version guard turns a “crash halfway” into a clear error and exit code 3 at the very start

Portability matrix: feature × shell

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.

Click a cell.
(after selecting a cell, examples and alternatives are shown)

Core commands

CommandPurposeNotes
checkbashisms script.shCheck #!/bin/sh bashisms in the scriptfrom 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 scriptcheck against the POSIX sh dialectreports SC3xxx; -s dash,-s busybox target specific implementations
dash -n script / bash --posix -nparse with the target shellsyntax check only
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash x.shrun on Bash 3.2simulate macOS's built-in Bash (user space is still BusyBox)
docker run --rm -v "$PWD":/w -w /w busybox:1.37 sh x.shrun on BusyBox ashthe tools are also all BusyBox versions
echo "$BASH_VERSION" "${BASH_VERSINFO[0]}"runtime versionempty when not bash
ls -l /bin/sh,readlink -f /bin/shsee what /bin/sh points toUbuntu: /bin/sh -> dash

1. Experience bashisms live with dash (measured on this machine)

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

2. The most dangerous one: &> in dash

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.

3. checkbashisms and shellcheck -s sh

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]

4. POSIX version

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

Lab 6: run opsctl on three shells (about 6 min)

dash: does the version guard take effect:
cd ~/bashlab/opsctl
sh bin/opsctl help; echo "rc=$?"         # on Ubuntu, sh is dash
opsctl: please run with bash, not sh
rc=3
Bash 3.2 (simulating the macOS built-in):
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.

Run the full test suite on the minimum supported version:
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.

BusyBox: write a truly portable install script:
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.

Case 1: a Docker entry script fails on Alpine

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.

Case 2: a macOS developer's script partially fails in CI (Ubuntu)

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.

Case 3: bashisms in Debian maintainer scripts

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).

Common errors and fixes

sh: 1: [[: not found

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
declare: -A: invalid option

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
${arr[@]}: unbound variable (empty array + set -u)

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.4
/usr/bin/env: ‘bash\r’: No such file or directory

Cause: 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 .
date: invalid date ‘2 days ago’ (BusyBox / macOS)

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
Command-line exercises
1. Rewrite if [[ $f == *.log ]]; then echo -e "log:\t$f"; fi as POSIX sh.
case $f in
  *.log) printf 'log:\t%s\n' "$f" ;;
esac
2. Write a version guard that uses only POSIX syntax and requires Bash ≥ 5.0.
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 expanded
Scenario analysis
You need to write a “one-line install” script (curl -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.

Verified instructional videos

▶
"Overcoming the limitations of the POSIX shell command language" - Curtis Millar (LCA 2021 Online) — linux.conf.au
English conference talk · limits of POSIX sh and how to handle them; the first choice for this module
▶
My thoughts on bash vs. Posix Compliant Shell Scripts. I am Mr. You Suck at Programming. — You Suck at Programming
English · a view on the trade-offs between Bash and POSIX-compatible scripts
▶
Shell Script Tutorial: A Look At Posix Compliant Shell Operators — Brodie Robertson
English · POSIX-compatible operators and syntax

Official and primary sources

Video storyboard script (about 80 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: the same script runs on three machines: Ubuntu reports “[[: not found”, the Mac reports “invalid option”, and Alpine reports “unexpected (”.
Narration: portability problems never show up on your own machine.
Shot 2 · 20–50s
Visual: concentric circles, with POSIX at the innermost ring, and outward in order Bash 3.2, Bash 4, Bash 5.3.
Narration: first decide which ring the script belongs to: either pure POSIX, or an explicitly required Bash version.
Shot 3 · 50–80s
Visual: the output of checkbashisms and shellcheck -s sh; three containers run the tests side by side and all pass.
Narration: check with tools, verify with containers. dash's &> reports no error; it just quietly empties the file.
or score ≥ 70% on the quiz

Module 7 · When not to use Bash: signals for migrating to Python / Go

42:00 – 50:00 · Bash is the best “glue” but not a good “foundation”: recognize the signals that you have outgrown it, and migrate step by step with contract tests
8 minPython 3 · Go · Ansible★★★★☆
Learning objectives
  • List Bash's “sweet spots” and “no-go zones”, and name at least 8 signals that you should switch languages or tools.
  • Choose a replacement based on the type of problem: Python, Go, Ansible, Make/just, jq/yq + a little Bash.
  • Migrate using the strangler pattern: keep the CLI contract unchanged, cross-check with bats contract tests, and migrate one subcommand at a time.
Prerequisites: the contract tests from M4, and the performance boundaries from M5. Importance:★★★★☆ (avoid writing the next 1,400-line “legacy script”)

What: Bash's sweet spot

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.

Signals that it is time to switch languages (or tools)

#SignalWhy Bash is not good at itMore suitable
1the 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 countPython / Go
2needs 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 nestingPython (dict/list), Go (struct)
3heavy reading and writing of JSON/YAML, not just extracting one or two fieldsrequires jq/yq round trips; quoting and escaping are very error-pronePython, Go; a few value extractions with jq are fine
4floating-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
5needs 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)
6concurrency that needs shared state (worker pools, rate limiting, aggregating results)&/wait -n/xargs -P only suitable for independent tasksGo (goroutines, channels), Python (concurrent.futures / asyncio)
7long-running processes, HTTP services, long-lived daemonssignals, memory, logging and health checks all have to be assembled by handGo, or Python + systemd
8needs to run natively on Windows, or is distributed to uncontrolled machinesdepends on Bash version and GNU/BSD tool differencesGo (a single static binary)
9handling untrusted input and concatenating commands (eval,ssh host "$cmd")high risk of quoting and injection problems; hard to auditPython (subprocess.run([...]) argument lists), Go (exec.Command)
10performance is still insufficient after optimization is exhausted (M5)interpreted execution: every external command is a fork/execGo, 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 planTerraform

Why: the cost of going out of bounds

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.

How: strangler migration (strangler)

  1. Freeze the contract: use bats to write contract tests for the existing behavior (M4): usage, exit codes, stdout format, stderr keywords. These tests are the acceptance criteria for the migration.
  2. Migrate one subcommand at a time: for example 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" "$@".
  3. Cross-check: the old and new implementations produce byte-identical output on the same inputs (including edge cases: empty files, bad lines, huge files); the contract tests all pass against the new implementation.
  4. Canary: use an environment variable switch (OPSCTL_IMPL=py) to give it to some users first; once stable, delete the old implementation.
  5. End state: when most subcommands have been migrated, the entry point itself is also switched to Python (argparse/click) or Go (cobra), and Bash keeps only the truly glue parts (such as the install script).

When: Python or Go?

PythonGo
distributionneeds an interpreter and dependencies (venv, uv, pipx); the system python3 varies by versiona single static binary, cross-compiled for Linux/macOS/Windows
development speedfast; the standard library covers json, csv, re, pathlib, subprocess, argparsemedium; the type system is stricter
concurrencygood 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 todata processing, reporting, upgraded glue, teams familiar with PythonCLIs distributed to many machines, long-running services, high concurrency
Common misconceptions① “Using Bash means you don't need to install anything”—once the script depends on jq, yq, GNU sed or Bash 5, that advantage disappears. ② “A one-shot rewrite is the fastest”—a big-bang rewrite often loses a lot of implicit behavior; contract tests plus migrating one subcommand at a time is safer. ③ “Python always starts slower than Bash, so it is unsuitable for CLIs”—Python starts in tens of milliseconds, which usually does not matter for ops tools; only for truly sensitive cases (hundreds of calls per second) consider Go. ④ “Switching languages means you no longer need shell knowledge”—Python's subprocess.run(..., shell=True) still has injection and quoting problems; pass argument lists instead.

Figure 7-1: decision tree for choosing a tool

Want to automate something converge multiple hosts to a desired state?Yes → Ansible manage the lifecycle of cloud resources?Yes → Terraform mainly calling existing commands?Yes → Bash (+ awk/jq) out-of-bounds signals appear (tables 1–10)?No → keep using Bash, add tests Pythondata processing · reports · upgraded glue Godistribution · concurrency · long-running services
Figure 7-1 first asks “is this a configuration management or infrastructure problem?”, then “is this just glue?”, and finally checks for out-of-bounds signals

Figure 7-2: strangler migration

bin/opsctldispatch (contract unchanged) cmd::servers (Bash) logs → logs_report.py cmd::health (Bash) bats contract tests (the same set)usage · exit codes · stdout format · stderr keywords+ cross-check: byte-by-byte diff of old and new implementations
Figure 7-2: users and downstream scripts do not notice the migration; the tests keep behavior consistent

“Should we switch languages?” scorer

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.

Score 0: keep using Bash

Tick the signals on the left.

The same task: Bash + awk vs Python

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.

Bash + awk version (glue + dedicated tool, entirely appropriate)

awk '$9 ~ /^[0-9][0-9][0-9]$/ {c[$9]++} END {for (k in c) print k, c[k]}' access.log | sort

Python version (when it needs to grow into a more complex report)

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

Cross-check (old and new implementations must produce identical output)

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.

Strangler step one: new subcommand opsctl codes, with both implementations sharing one entry point

Lesson 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.

Lab 7: verify two implementations with the same test suite (about 7 min)

Prepare fixtures:
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
Write one test that runs against both implementations:
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.

Evaluate opsctl itself: on the “Animation” page, click “Load the current state of opsctl v1.0”, record the score, and write down which subcommand you think opsctl will need to migrate first, and why (hint: deploy involves multiple hosts, consider Ansible).

Case 1: a 1,400-line release script

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.

Case 2: replacing an SSH loop with Ansible

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.

Case 3: a tool distributed to 300 developer machines

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).

Common problems during migration

Symptom: the Python version's output “looks the same” as the Bash version, but the diff shows everything different

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
python3: command not found (or the version is too old and does not support list[str] annotations)

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.

Symptom: injection or quoting problems when subprocess calls shell commands

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
Symptom: after migration the exit code convention is broken and downstream scripts misjudge

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.

Command-line exercises
1. Use jq to extract all prod host names from ~/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.
2. Safely call 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)
Scenario analysis
The opsctl team needs to add 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.

Verified instructional videos

▶
Python or Bash for scripting? Which is best? — Mashed
English · trade-offs between Bash and Python for scripting; the first choice for this module
▶
Python vs. Bash: Why Python CRUSHED Bash for DevOps Automation — TechTalks with Gil - SRE
English · from an SRE perspective, why complex automation should move to Python (the view leans toward Python; weigh it against this module's “sweet spot” discussion)

Official and primary sources

Video storyboard script (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: a script's line counter climbs from 50 to 1,400, while “incident” icons light up one by one beside it.
Narration: an out-of-bounds Bash script does not suddenly break; it slowly becomes a script nobody dares to change.
Shot 2 · 20–45s
Visual: the signal checklist ticks off one by one: nested data, floating point, concurrent shared state, cross-platform.
Narration: when these signals appear, consider Python, Go, or a dedicated tool such as Ansible.
Shot 3 · 45–75s
Visual: opsctl's dispatch diagram; one subcommand's box turns into a Python icon, and the same bats test suite passes below.
Narration: the contract tests stay the same; migrate one subcommand at a time, and users notice no change at all.
or score ≥ 70% on the quiz

Module 8 · opsctl v1.0: testing, CI and release

50:00 – 60:00 · Tie the first 7 modules into one pipeline: make check does the same thing locally and in CI; tagging publishes a tarball with checksums
10 minGitHub Actions · actions/checkout v7.0.1 (SHA pinned)★★★★★
Learning objectives
  • Define lint,fmt,fmt-check,test,check, and release targets with a Makefile (or justfile), so local and CI run exactly the same commands.
  • Write a GitHub Actions workflow: pin actions by commit SHA, pin ShellCheck/shfmt/bats versions, use least privilege, and check out submodules.
  • Make reproducible releases with the VERSION file + git tags + git archive + sha256sum and verify version consistency in CI.
  • When CI fails, quickly locate the problem along the path “which step failed → read the log → reproduce locally”.
Prerequisites: M2–M4,GitHub 8 hoursfor the Actions basics. Importance:★★★★★

What: what v1.0 means

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.

The final project structure

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

Why: why use make check instead of writing the commands directly into CI

  • Define once: developers locally 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).
  • Portable: when moving to GitLab CI or Jenkins, the pipeline still just runs make check (see GitLab,Jenkins courses).
  • Readable: the Makefile is the document that answers “what quality checks does this project have?”

How: the three “pins” of supply-chain security

ObjectApproachReason
third-party actionuses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1Tags can be moved; commit SHAs cannot. Keep a human-readable version number in a comment; Dependabot updates both the SHA and the comment.
tool versionsCI downloads ShellCheck v0.11.0 and shfmt v3.14.1 by version number; bats is pinned to v1.14.0 via a submoduleubuntu-latest Versions preinstalled on the image change, and new versions may add warnings
token permissionspermissions: contents: read; only the release job contents: write; persist-credentials: falseleast 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.

When: release process

  1. Develop on a feature branch; a PR triggers CI (make check).
  2. After merging to main, change VERSION to 1.0.0, update CHANGELOG, and commit.
  3. git tag -a v1.0.0 -m "opsctl 1.0.0" && git push origin v1.0.0.
  4. The tag triggers the release job: verify VERSION matches the tag → git archive → sha256sum → create the GitHub Release and upload.
  5. After downloading, the user runs sha256sum -c to verify, then runs install.sh.

Makefile vs justfile comparison

makejust
Preinstalledalmost all Unix-like systems have itneeds to be installed (1.59.0, 2026-10)
Syntax pitfallsrecipes must be indented with Tab ; variables $(VAR) are distinguished from Shell's $$var ; each line runs in a separate shell by defaultspace indentation is fine; {{var}} interpolation; more friendly error messages
suited toneeds zero dependencies, or already has the make ecosystempure task runner
Common misconceptions① “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.

Figure 8-1: from commit to release

git pushPR / main checkoutSHA pins + submodules install toolsdownload pinned versions make lintShellCheck make fmt-checkshfmt -d make testbats test/ git tag v1.0.0push tag check job passesneeds: check VERSION == tag?otherwise fail git archive+ sha256sum gh releasecontents: write any step fails: later steps do not run, and the PR cannot be merged (branch protection requires check to pass) release artifacts come only from the tagged commit: reproducible, verifiable
Figure 8-1 top: the check job on every push; bottom: the release job triggered by a tag

CI pipeline simulator

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).

Choose a commit scenario.
Waiting for push…

1. Makefile

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).

2. justfile (optional, equivalent to the Makefile)

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

3. GitHub Actions workflow

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.

4. Dependabot and .gitattributes

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.

Lab 8: release opsctl v1.0.0 (about 10 min)

Run all gates locally (requires the M2 .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.

Bump the version, commit, and tag:
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"
Generate the release artifact locally and verify it:
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/
...
Install from the tarball and run a smoke test (inside ~/bashlab):
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
Push to GitHub and watch CI:
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

Case 1: a moved action tag

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.

Case 2: “passes locally, fails in CI”

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.

Case 3: local files got into the release artifact

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.

Interactive troubleshooting tree: what to do when CI is red

Start from “which step failed” and narrow down step by step; every conclusion comes with a local reproduction command and a fix.

Common errors quick reference

Makefile:16: *** missing separator. Stop.

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!)
fatal: no submodule mapping found in .gitmodules for path 'test/bats'

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"
Command-line exercises
1. Find 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>^{}'
2. A user receives 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
Scenario analysis
The team wants opsctl to also be verified by CI on developers' macOS machines, and to test the minimum supported Bash 4.4. How would you extend the workflow?

① 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.

Verified instructional videos

▶
How to use GitHub Actions | GitHub for Beginners — GitHub
English · an introduction to Actions from GitHub's official channel; the first choice for this module
▶
How to Test Docker Images and Shell Scripts (with bats-core) — Redhwan Nacef
English · integrating bats tests into an automated workflow
▶
GitHub Actions: Protecting Your CI from Attackers — SANS Cloud Security
English · background on CI supply-chain security (pinned SHAs, least privilege)

Official and primary sources

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided for a video tool to produce them.

Shot 1 · 0–20s
Visual: a terminal runs make check, and three output sections turn green in turn: ShellCheck, shfmt, bats.
Narration: local and CI run the same command; that is the first principle of quality gates.
Shot 2 · 20–50s
Visual: a uses line in the workflow file, with the tag replaced by a forty-character SHA, next to an animation of a “moved tag”.
Narration: pin actions to commit SHAs, pin tools to version numbers, and give tokens read-only permissions.
Shot 3 · 50–75s
Visual: git tag v1.0.0; the release job checks VERSION, generates the tarball and sha256 file, and the GitHub Release page appears.
Narration: release artifacts come only from the tagged commit, and users can verify them with checksums.
Shot 4 · 75–90s
Visual: the version output of opsctl 1.0.0, with 33 green check marks behind it.
Narration: 1.0 is a promise: usage, exit codes and output format are now protected by tests.
or score ≥ 70% on the quiz

Command cheat sheet

Debugging · ShellCheck · shfmt · bats · performance · portability · release — templates you can copy directly
Bash 5.3ShellCheck 0.11.0 · shfmt 3.14.1 · bats 1.14.0

Debugging

PurposeCommand / code
Trace the whole scriptbash -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 PS4PS4='+ ${BASH_SOURCE[0]##*/}:${LINENO}:${FUNCNAME[0]:-main}: ' (must use single quotes)
With timestampsPS4='+ ${EPOCHREALTIME} ${BASH_SOURCE[0]##*/}:${LINENO}: '
Write trace to a fileexec {fd}>>trace.log; BASH_XTRACEFD=$fd; set -x
Syntax checkbash -n f.sh; shfmt -d f.sh; dash -n f.sh
Call stackcaller 0; ${FUNCNAME[i]} ${BASH_SOURCE[i]} ${BASH_LINENO[i-1]}
ERR trapset -E; trap 'echo "ERR $? at ${BASH_SOURCE[0]}:$LINENO: $BASH_COMMAND" >&2' ERR
DEBUG trapset -T; trap 'echo "> $BASH_COMMAND" >&2' DEBUG
Inspect variables preciselydeclare -p var arr

ShellCheck

CodeOne-line descriptionFix
SC2086 (info)Unquoted variable"$var"; use an array when splitting is needed
SC2046 (warning)Unquoted command substitutionfind -exec … {} +,mapfile
SC2155 (warning)Declaration and assignment combined, masking the exit codelocal v; v=$(cmd)
SC2164 (warning)cd failure unhandledcd -- "$d" || exit
SC2181 (style)Use $? for indirect checkingif ! cmd; then
SC2034 (warning)Unused variableDelete / fix the spelling / export
SC2045 (error)Iterating over ls outputfor f in ./*
SC2115 (warning)rm -rf $d/*rm -rf -- "${d:?}"/*
SC2006 (style)Backticks$(…)
SC1091 (info)sourced file not followed-x + # shellcheck source=…
SC3xxxNon-portable constructs in POSIX shsee 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 and style

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.

bats test template

#!/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'
}
AssertionPurpose
assert_success / assert_failure [N]Exit code
assert_output 'x' / --partial / --regexp / refute_outputoutput 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 ! cmdassert the exit code directly when using run
bats --tap / --report-formatter junit -o reports / -f regex / --jobs NRun options

Performance substitution table

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 lineone awk
for f in …; do cmd "$f"; donefind … -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

Portability

BashPOSIX sh
[[ $a == b* ]]case $a in b*) … ;; esac
echo -eprintf
source f. ./f
arr=(a b)set -- a b
cmd &> fcmd >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

Signals to switch languages (if you see any three, take it seriously)

> 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).

Release

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

Capstone lab + final quiz

Take over a “legacy” log cleanup script: test it first, then fix it, then speed it up, then decide on portability, and finally release it as a new opsctl subcommand in v1.1.0
about 45 min~/bashlab/opsctldeletes files only inside ~/bashlab

Scenario

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
Static analysis (do not run): 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?).
Write characterization tests (characterization test): in 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.
Implementation 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.
Gates: 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.
Performance comparison: create 2,000 log files in a loop, and compare the legacy logic (2–3 forks per file) with the find version: hyperfine -w 1 --prepare '…rebuild test directory…' 'bash old.sh d 7' 'bin/opsctl cleanup d --days 7', record the speedup ratio.
Portability decision: opsctl requires Bash ≥ 4.4, but 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”.
Release v1.1.0: adding a subcommand is a backward-compatible new feature → bump the minor version by 1. Update 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.
Acceptance checklist

Open self-test (6 questions)

1. Why must PS4 be assigned with single quotes? Why does the trace in command substitution have two plus signs?

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 ++.

2. Explain why SC2155 is a warning rather than style, and give the concrete consequence under set -e.

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.

3. What is the difference between run and calling a command directly in bats? When is each used?

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).

4. What are the prerequisites and limitations of injecting test doubles via PATH?

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.

5. How would you decide whether to write a script as POSIX sh or Bash?

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”.

6. Why use git archive + tags for releases instead of packaging from the CI working directory? Why must actions be pinned to SHAs?

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.

Sources and version notes

Verified date: 2026-11-17
Official sources take precedence

Sources and verification conclusions

TopicVerification conclusionSources (accessed 2026-11-17)
Bash versionUbuntu 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 Windowspackages.ubuntu.com;GNU FTP bash-5.3-patches
xtrace, PS4, BASH_XTRACEFD, caller, trap, EPOCHREALTIMEsemantics 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.37GNU Bash Reference Manual
ShellCheckLatest 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-2ShellCheck releases;packages.ubuntu.com
shfmtLatest 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.0mvdan/sh releases;shfmt.1.scd (v3.14.1)
bats-core and helper librariesbats-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 Guide100-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 shfmtshellguide.html
dash / POSIXUbuntu 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 Windowspackages.ubuntu.com;packages.debian.org;dash.git
Other tool versionsdevscripts 2.26.7 (checkbashisms), hyperfine 1.19.0 (apt) / 2.0.0 (upstream 2026-10-07), busybox 1.37.0, just 1.59.0packages.ubuntu.com; GitHub releases
Container image tagsbash: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 existDocker Hub API
GitHub Actionsactions/checkout Latest v7.0.1, with the tag pointing to commit 3d3c42e5aac5ba805825da76410c181273ba90b1; ShellCheck/shfmt release asset file names verified against the release pagesGitHub API (gh api repos/actions/checkout/git/ref/tags/v7.0.1)

Video verification notes

All videos had their titles and channels verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17:

Video IDTitleChannelUsed for
nvAMWPeKBrc10 Tips for debugging Bash Scripts (actually useful and real-world applicable)You Suck at ProgrammingM1
LX-APA9ugMcBash Debug Mode ExplainedYou Suck at ProgrammingM1
Yw5qLN5bKPgDebugging Bash Scripts: The Power of set -e, set -x, set -o, and set -uDaily Dose of DevM1
28Ygo05cLmoLinting and Improving Your Bash Scripts with ShellCheckNick JanetakisM2
zFDYVzU6JxAI Learned Something New about Bash from `shellcheck`You Suck at ProgrammingM2
GToQwmDXUx8SC2086: The Bash Quoting Bug to Fix Before You Schedule a ScriptFutureOpsM2
lmt7rrMW_pUWrite Better Bash Scripts! Use ShellCheck and shfmtTom on the InternetM3
OqWacbx5rLoCreate BULLET PROOF Shell Scripts with ShellCheck and Neovim!DevOps ToolboxM3
SB7e5qdGh9EHow to Test Docker Images and Shell Scripts (with bats-core)Redhwan NacefM4, M8
EHUE3i8izewTest-Driven Development (TDD) Tutorial: Unit Testing Bash Scripts with Bats on Rocky Linux 10theurbanpenguinM4
sJ5LHe22IU0fork and exec Explained #bashTruly CodingM5
hl3siAyoQ-wBash Scripting : Source and Fork your ScriptstheurbanpenguinM5
oKA2aK0-tb4"Overcoming the limitations of the POSIX shell command language" - Curtis Millar (LCA 2021 Online)linux.conf.auM6
PPiPbMFKDHYMy thoughts on bash vs. Posix Compliant Shell Scripts. I am Mr. You Suck at Programming.You Suck at ProgrammingM6
LjGwm0Z6D24Shell Script Tutorial: A Look At Posix Compliant Shell OperatorsBrodie RobertsonM6
RQEh8XW0wLkPython or Bash for scripting? Which is best?MashedM7
ASTpo4e7q9cPython vs. Bash: Why Python CRUSHED Bash for DevOps AutomationTechTalks with Gil - SREM7
BQrohJ3PT7IHow to use GitHub Actions | GitHub for BeginnersGitHubM8
UrODXOiqH0kGitHub Actions: Protecting Your CI from AttackersSANS Cloud SecurityM8

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.

Audio narration notes

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.

Known limitations

  • ShellCheck, shfmt and bats were not run in the authoring environment (the authoring machine did not have them installed, and system packages were not installed as required). Their outputs are all examples: warning text comes from the rule descriptions in the ShellCheck wiki and source, and bats/bats-assert output formats come from the official docs; column numbers, line numbers, version strings, colors and details depend on actual results.
  • Output labeled “actual run results” was executed on Windows in the Git for Windows environment (Bash 5.2.37, bundled dash, Python 3.14); values on Linux (especially M5 timings) will differ noticeably, but the relative relationships hold. Some Bash 5.3 error messages (such as the bash -n “unexpected end of file” message, which adds unclosed compound command information) have not been tested on 5.3.
  • The tests in this lesson target the actual code from the Lesson 3–6 courseware: when writing, the Lesson 3 capstone lab (v0.1), Lesson 4 Module 8 (v0.2: 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.
  • If your Lesson 3–6 implementation differs from the courseware (for example, if you changed log text or option names yourself), simply adjust the expected values in the tests. Lesson 5's logs report was not modified; M7 creates a separate codes subcommand to demonstrate migration.
  • shfmt's formatting of the Lesson 3–6 code was not tested (this code has alignment spaces and single-line case branches; the first shfmt -d run will likely produce a diff); run make fmt , then review and commit separately.
  • The ShellCheck / shfmt binaries downloaded in the CI workflow are not verified with SHA-256 (no official checksums are built into this lesson). For production use, add a verification step, or switch to a setup action with a pinned SHA that you trust. ubuntu-24.04 Runner availability and preinstalled software follow the GitHub documentation.
  • The BusyBox ash column in the M6 matrix depends on BusyBox's compile options and was not tested item by item in a busybox container; the macOS /bin/sh 's implementation details (Bash 3.2 in POSIX mode, switchable to dash) come from public Apple platform materials and community documentation.
  • The process counts in the M5 animation are theoretical estimates of “1 subshell for command substitution + 1 process per pipeline segment”; Bash optimizes some cases such as the last pipeline segment, so strace measured values may be slightly lower.