Bash Lesson 1: How Bash Works — Command Line and Shell Mechanics

Starting from “what happens after you press Enter”: interactive vs script, types of commands, quoting, the seven-step expansion, redirection and file descriptors, pipes and exit status, variables and subshells, and finally writing your first executable script
Bash 5.3 (patch 5.3.20)Compared with 5.2 / macOS 3.2Local only · FreeVerified · 2026-11-17
Position in the Learning Path Linux → Bash → Git → Docker → Kubernetes → Terraform → Ansible → GitHub → GitLab → Azure DevOps → Jenkins → Azure Landing Zone → AKS → Helm → GitOps and Argo CD → Prometheus & Grafana. The prerequisite course is Linux 8 + 1-hour course: Lesson 1 there covers the system-call view of “what happens when you run a command,” and Lesson 5 covers image building, patching and logging, whose ops-script points link directly to this lesson. This course is a systematic deep dive into Bash itself— it does not repeat Packer, but instead covers shell parsing, expansion, redirection, scope, error handling, text processing, testing and release in depth, and applies them through a project that runs throughout the course opsctl (created in Lesson 3) to put them into practice.
Overall Learning Objectives
  • Distinguish interactive / non-interactive, login / non-login shells, state which startup files Bash reads in each case, and explain the shebang (#!) is handled by the kernel rather than by Bash.
  • Use type -a / command -v to determine whether a name is an alias, keyword, function, builtin or external command, and know the order in which Bash searches for commands and its hash cache.
  • Correctly use single quotes, double quotes,$'…' and backslashes, and predict how many “words” any command line is split into.
  • Recall and apply the order of the seven expansions: brace → tilde → parameter/variable, arithmetic, command substitution (left to right) → word splitting → pathname expansion, then quote removal — and explain x='{a,b}'; echo $x why something is not expanded.
  • Master redirection and file descriptors: > >> 2>&1 &> <<< exec 3>, including the order trap of “copying fds from left to right.”
  • Understand pipes, exit status,&& / ||,PIPESTATUS,pipefail, and know what 126 / 127 / 128+N mean.
  • Understand shell variables vs environment variables,export, subshells, and “lost variables”, laying the groundwork for Lesson 2's scope animation.
  • Turn a one-line command into an executable, readable, reusable script: shebang, permissions, arguments, exit codes,bash -n and set -x debugging — this lesson's core animation runs through every module: the parsing and execution pipeline of a command line.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/bashlab)
0Before ClassEnvironment setupBash 5.x environment (Ubuntu 26.04 / WSL2 / macOS + Homebrew / container bash:5.3),~/bashlab,make-data.sh to generate the sample datasetEnvironment self-check checklistGenerate ~/bashlab/data/ and verify checksums
100–06What Is a ShellTerminal / Shell / kernel; interactive and script; login and non-login; startup files; shebangStartup file read simulatorUse $-,shopt login_shell to identify the shell type
206–13Types of commandsaliases, keywords, functions, builtins, external commands; lookup order; hash; command / builtinCommand lookup resolverMake one name an alias, a function and an external command at the same time
313–21QuotingSingle quotes, double quotes,$'…', backslashes,printf %qInteractive “tokenizer”: see how a command is split into wordsHandling files/ odd names in
421–28Seven-step expansionbrace, tilde, parameter, arithmetic, command substitution, word splitting, pathname, quote removal; Bash 5.3's ${ cmd; }core animation: the parsing and execution pipeline of a command lineUse set -x to observe expansion results
528–35Redirection and fdfd 0/1/2,> >> 2>&1 &>, here-doc / here-string,exec opening fds, noclobberfile descriptor table animation (order trap)Split access.log statistics and errors into separate files
635–42Pipes and exit statuspipeline concurrency and subshells,$?,PIPESTATUS,pipefail,&& || !Pipe / short-circuit evaluation simulatorCount 5xx responses, top IPs, and correctly capture each stage's exit code
742–50Variables, environment and subshellsshell variables vs environment variables,export, prefix assignments,( ) and { },BASHPIDprocess and environment inheritance animationProve | while read that the count is lost
850–60First scriptshebang,chmod +x, PATH, arguments $1 "$@", exit codes,bash -n,set -x,source vs executionscript execution path animation + interactive troubleshooting treeWrite ~/bashlab/bin/datainfo
—After ClassCheat sheet · Integrated labWrite dataset-check.sh: safely traverse oddly named files, split logs, and return meaningful exit codesFinal quiz (12 questions)The script ~/bashlab/data passes all acceptance checks on

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Identify shell type and startup files✓·····✓✓echo $-,shopt login_shell,bash -lM1
Distinguish command types and lookup order·✓·✓···✓type -a,command -v,hashM2
Use quoting correctly··✓✓✓·✓✓"$var",$'\t',printf %qM3, integrated lab
Predict expansion results and order·✓✓✓···✓set -x,{a..c},$(( )),$( )M4
Redirection and file descriptors···✓✓✓·✓2>&1,&>,exec 3>,<<<M5, integrated lab
Pipes and exit status·✓·✓·✓✓✓$?,PIPESTATUS,set -o pipefailM6, integrated lab
Variables, environment and subshells✓····✓✓✓export,declare -p,env,( )M7
Write and debug executable scripts✓✓✓✓✓✓✓✓#!/usr/bin/env bash,chmod +x,bash -n,bash -xM8, integrated lab
Safely handle odd filenames··✓✓·✓·✓for f in ./*,--,printf %qM3, integrated lab

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
all forms of parameter expansion (${var:-x},${var%.*}…), arithmetic, arrays,[[ ]], loops,read / mapfile, process substitutionRequires first mastering this lesson's expansion order and quotingLesson 2: Control Flow and Data
functions,local dynamic scope, nameref, libraries and modularization,opsctl skeletonbelongs to script engineeringLesson 3
set -euo pipefail full exception rules,trap, locks, logging, retriesThis lesson only previews pipefail, while strict mode needs an hour of its ownLesson 4
in-depth grep / sed / awk / find / xargs / jq / yqbelongs to text and data processingLesson 5 (Linux Lesson 1, Module 7 has an introduction)
health checks, backups, deployment scripts; ShellCheck, shfmt, bats testing and CIbelongs to operations practice and quality assuranceLessons 6–7; CI is also covered in the GitHub course / the GitLab course
bulk configuration of many hosts, idempotent configuration managementbeyond the reasonable limits of Bashthe Ansible course
Packer image building, system-call-level strace analysisCovered in the prerequisite coursethe Linux course Lessons 1 and 5

How to use these materials

10 pages per module
Principles · Diagrams · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Audio · Video. Read “Principles” and “Animation” first, then go to ~/bashlab do the “Lab” there. The “parsing and execution pipeline” in Module 4 is the main thread of the whole course; the animations in the other modules each zoom in on one part of it.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress, saved in this browser's local storage (if the browser blocks local storage, it is cleared on refresh).
Chinese Voice
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the script aloud, with English terms pronounced in en-US; without a Chinese voice pack the script can still be read, or passed to a TTS tool to generate audio.
Version notes Verified 2026-11-17. The course baseline is GNU Bash 5.3 (released 2025-07; the official patches on ftp.gnu.org have reached bash53-020, 2026-09-14), i.e., the version shipped with Ubuntu 26.04 LTS; the official Docker Hub image has bash:5.3 / bash:5.3.20 tags. Bash 5.3's new features (command substitution without fork ${ cmd; } and ${| cmd; },GLOBSORT,BASH_TRAPSIG,source -p,read -E etc.) are marked “5.3+” in the relevant modules. 5.2 On Ubuntu 24.04, Debian 12, etc., 95% of this lesson's content is identical; macOS's bundled /bin/bash is 3.2.57 (it has never been upgraded because of GPLv3 licensing; the default interactive shell on macOS is already zsh), and it lacks associative arrays,mapfile,${var,,},{fd}> etc. Install a newer version with Homebrew. Ubuntu 26.04 defaults to the Rust implementation of coreutils (uutils),ls,sort and similar tools may differ from the GNU versions in some options and error messages —this does not affect Bash's own behavior, since this lesson covers only Bash's syntax and mechanics.

Module 0 · Environment setup: Bash 5.x lab environment and ~/bashlab

Prepare a Bash 5.x environment and create the working directory ~/bashlab, use make-data.sh to generate the sample dataset shared across the course ~/bashlab/data/— Lessons 2–8 all use it directly
Before class ≈ 10 minRuns locally · FreeDeletion operations are done only inside ~/bashlab
Prerequisites
  • Completed (or familiar with)Linux 8 + 1-hour course Lesson 1: able to use a terminal and knows basic concepts of file permissions and processes.
  • Any one Bash 5.x environment (see the table below). Not required: any cloud account; all labs in this lesson are purely local.
  • A plain-text editor (nano,vim or VS Code). Scripts must be saved with LF line endings: CRLF line endings from Windows editors will cause $'\r': command not found (Module 8 troubleshooting).

Choose an environment

OptionBash versionHow toNotes
A. The linuxlab VM from the Linux course (recommended)Ubuntu 26.04: 5.3; 24.04: 5.2multipass shell linuxlab or SSH login labadmin26.04's coreutils default to the Rust version (uutils); when GNU behavior is needed, use gnu prefixed commands (see Linux Lesson 1, Module 2)
B. WSL2depends on the distribution (Ubuntu 26.04 is 5.3)wsl --install -d <distribution name> (the name shown by wsl --list --online is authoritative)Always put lab directories in the Linux home directory (~/bashlab),not in /mnt/c: NTFS does not allow file names to contain * " newlines and similar characters,files/ so the odd-named files in it will fail to be created.
C. macOS + HomebrewHomebrew's bash formula provides 5.3brew install bash, then use $(brew --prefix)/bin/bash to start it/bin/bash is still 3.2.57; scripts that use #!/usr/bin/env bash pick up the newer version on PATH. The BSD version sed/date/stat differs from GNU (compared in Lesson 5)
D. Containerbash:5.3 (official Docker image, based on Alpine)docker run --rm -it -v "$HOME/bashlab":/root/bashlab -w /root/bashlab bash:5.3In the image, Bash is located at /usr/local/bin/bash,/bin/sh and ls/sort etc. come from BusyBox, and their output format differs from GNU; when needed, apk add coreutils. -v Mount so that data stays on the host

Git Bash on Windows (MSYS2, Bash 5.2) can also run most of this lesson's pure-Bash examples — the outputs marked “Actual result (Bash 5.2)” in these materials were measured on Git Bash 5.2.37 — but it does not have real fork, file permissions and Linux's /proc, so use A–D for labs involving permissions and processes.

Confirm Bash version

bash --version | head -n1
echo "$BASH_VERSION"
printf '%s.%s\n' "${BASH_VERSINFO[0]}" "${BASH_VERSINFO[1]}"
command -v bash; echo "$SHELL"
GNU bash, version 5.3.3(1)-release (x86_64-pc-linux-gnu)
5.3.3(1)-release
5.3
/usr/bin/bash
/bin/bash

Patch level (5.3.3 the 3 in ) depends on how many official patches the distribution has applied, so use your own output as the reference. $SHELL is login shell (from /etc/passwd), not necessarily the shell you are currently running; to check the current shell, use $BASH_VERSION whether it is non-empty or ps -p $$ -o comm=.

Create the working directory

mkdir -p ~/bashlab/{data,tmp,bin,scripts}
cd ~/bashlab && ls -F
bin/  data/  scripts/  tmp/
DirectoryPurposeWhich lesson uses it
~/bashlab/data/Sample dataset (generated by make-data.sh; can be rebuilt at any time)All lessons
~/bashlab/tmp/Temporary output from labs; safe to deleteAll lessons
~/bashlab/bin/Your own small tools (added to PATH in Module 8)Lessons 1–2
~/bashlab/scripts/Practice scriptsAll lessons
~/bashlab/opsctl/Running project opsctl (bin/ lib/ etc/ test/)Created in Lesson 3, evolved in Lessons 4–7, referenced in Lesson 8

make-data.sh: generate the course's sample dataset

Save the script below as ~/bashlab/make-data.sh (recommended: nano ~/bashlab/make-data.sh, paste,Ctrl+O and save). It is deterministic: it does not use $RANDOM, does not read the current time, and instead uses a fixed-seed linear congruential generator, so the output generated on any machine access.log are byte-for-byte identical, so later lessons can cite facts such as “line 458” and “28 5xx lines in total.” The script is compatible with Bash 3.2+ and depends only on printf,mkdir,rm,touch.

#!/usr/bin/env bash
# make-data.sh —— Generate the sample dataset for the Bash 8-hour course (provided in Lesson 1, reused in Lessons 2–8)
#   Usage: bash ~/bashlab/make-data.sh [target directory]      Default target directory: ~/bashlab/data
#   Features: deterministic (no $RANDOM, no reading of system time; the same script generates identical content on any machine)
#         Compatible with Bash 3.2+ (also runs on the bash bundled with macOS); depends only on printf / mkdir / rm / touch
set -euo pipefail

DATA_DIR="${1:-$HOME/bashlab/data}"
case "${DATA_DIR%/}" in
  */data) ;;                                   # Safety guard: only allow deleting and recreating a directory named data
  *) printf 'make-data.sh: target directory must end with /data: %s\n' "$DATA_DIR" >&2; exit 2 ;;
esac
DATA_DIR="${DATA_DIR%/}"
rm -rf -- "$DATA_DIR"
mkdir -p -- "$DATA_DIR/files/sub dir"

# ---------- Deterministic pseudo-random numbers: linear congruential generator (LCG), fixed seed ----------
seed=20261117
rnd() {                        # rnd N  → put a random number in 0..N-1 into variable R
  seed=$(( (seed * 1103515245 + 12345) % 2147483648 ))
  R=$(( (seed / 65536) % $1 ))
}

# ---------- 1) access.log: nginx / gunicorn combined format ----------
ips=(203.0.113.7 198.51.100.23 192.0.2.10 192.0.2.11 192.0.2.12 10.10.1.21 10.10.1.22 10.20.1.31 172.16.5.4 203.0.113.99)
paths=(/ /healthz /healthz /api/orders /api/orders /api/orders /api/orders/1042 /login /static/app.js)
uas=('curl/8.12.1'
     'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'
     'Mozilla/5.0 (Macintosh; Intel Mac OS X 15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15'
     'kube-probe/1.37'
     'python-requests/2.32.5')
log="$DATA_DIR/access.log"
: > "$log"
t=$(( 10 * 3600 ))                              # starting at 10:00:00
emit() {                                        # emit IP METHOD PATH STATUS BYTES UA
  local hh=$(( t / 3600 )) mm=$(( t % 3600 / 60 )) ss=$(( t % 60 ))
  printf '%s - - [17/Nov/2026:%02d:%02d:%02d +0000] "%s %s HTTP/1.1" %s %s "-" "%s"\n' \
    "$1" "$hh" "$mm" "$ss" "$2" "$3" "$4" "$5" "$6" >> "$log"
}
t=$(( t + 1 ))
emit 203.0.113.7 GET /healthz 200 2 'curl/8.12.1'          # line 1 is fixed as the example from the course spec
for (( i = 2; i <= 600; i++ )); do
  rnd 7;  t=$(( t + R ))
  rnd ${#ips[@]};   ip=${ips[R]}
  rnd ${#paths[@]}; p=${paths[R]}
  rnd ${#uas[@]};   ua=${uas[R]}
  m=GET
  case $p in
    /healthz) st=200; bytes=2; ua='kube-probe/1.37' ;;
    /login)   rnd 4; if (( R == 0 )); then m=POST; st=302; bytes=0; else st=200; bytes=1532; fi ;;
    /api/orders)
      rnd 3; (( R == 0 )) && m=POST
      rnd 20
      if   (( R == 0 )); then st=500; bytes=0
      elif (( R == 1 )); then st=503; bytes=0
      elif (( R == 2 )); then st=400; bytes=48
      elif [[ $m == POST ]]; then st=201; rnd 400; bytes=$(( 180 + R ))
      else st=200; rnd 4000; bytes=$(( 900 + R )); fi ;;
    /api/orders/1042) rnd 5; if (( R == 0 )); then st=404; bytes=21; else st=200; bytes=$(( 300 + R )); fi ;;
    /static/app.js) rnd 3; if (( R == 0 )); then st=304; bytes=0; else st=200; bytes=48213; fi ;;
    /) rnd 6; if (( R == 0 )); then st=301; bytes=169; else st=200; bytes=4120; fi ;;
  esac
  emit "$ip" "$m" "$p" "$st" "$bytes" "$ua"
  # Fixed “story” records for later lessons' exercises to query
  if (( i == 150 )); then                       # brute-force login: same IP gets 6 consecutive 401s
    for k in 1 2 3 4 5 6; do t=$(( t + 1 )); emit 198.51.100.23 POST /login 401 64 'python-requests/2.32.5'; done
  fi
  if (( i == 300 )); then                       # quotes and apostrophes: by default nginx logs the UA's " as \x22
    t=$(( t + 2 )); emit 192.0.2.66 GET / 200 4120 "O'Reilly-Bot/2.0 (it's \\x22quoted\\x22; +https://example.com/bot)"
  fi
  if (( i == 450 )); then                       # a burst of 502s: upstream gunicorn restarted
    for k in 1 2 3 4; do t=$(( t + 1 )); emit 10.20.1.31 GET /api/orders 502 157 'curl/8.12.1'; done
  fi
done

# ---------- 2) servers.csv and 3) inventory.json: the same data ----------
# Fields: name|env|region|ip|role   (the comma in role demonstrates a CSV edge case)
servers=(
  'web-01|dev|canadacentral|10.10.1.21|web'
  'api-01|dev|canadacentral|10.10.1.22|api'
  'db-01|dev|canadacentral|10.10.1.23|db'
  'web-01|staging|ca-central-1|10.20.1.31|web'
  'api-01|staging|ca-central-1|10.20.1.32|api'
  'db-01|staging|ca-central-1|10.20.1.33|db'
  'web-01|prod|canadacentral|10.30.1.41|web'
  'web-02|prod|canadacentral|10.30.1.42|web'
  'api-01|prod|canadacentral|10.30.1.43|api'
  'edge-01|prod|ca-central-1|10.30.2.51|web,api'
  'db-01|prod|canadacentral|10.30.1.44|db'
  'bastion-01|prod|ca-central-1|10.30.2.10|bastion'
)
csv="$DATA_DIR/servers.csv"; json="$DATA_DIR/inventory.json"
printf 'name,env,region,ip,role\n' > "$csv"
printf '[\n' > "$json"
n=${#servers[@]}; idx=0
for row in "${servers[@]}"; do
  IFS='|' read -r name env region ip role <<< "$row"
  case $role in *,*) role_csv="\"$role\"" ;; *) role_csv=$role ;; esac
  printf '%s,%s,%s,%s,%s\n' "$name" "$env" "$region" "$ip" "$role_csv" >> "$csv"
  idx=$(( idx + 1 )); sep=','; (( idx == n )) && sep=''
  printf '  {"name": "%s", "env": "%s", "region": "%s", "ip": "%s", "role": "%s"}%s\n' \
    "$name" "$env" "$region" "$ip" "$role" "$sep" >> "$json"
done
printf ']\n' >> "$json"

# ---------- 4) config.yaml: opsctl's sample config ----------
cat > "$DATA_DIR/config.yaml" <<'YAML'
# opsctl sample config (Bash 8-hour course; read by the opsctl and yq examples from Lesson 3 onward)
opsctl:
  version: "0.1"
  log_level: info            # debug | info | warn | error
  default_env: dev
  inventory: ~/bashlab/data/servers.csv
environments:
  dev:
    region: canadacentral
    health_url: http://10.10.1.21:8080/healthz
  staging:
    region: ca-central-1
    health_url: http://10.20.1.31:8080/healthz
  prod:
    region: canadacentral
    health_url: https://shop.example.com/healthz
    require_confirm: true
health:
  timeout_seconds: 5
  retries: 3
  backoff_seconds: [1, 2, 4]
backup:
  dest: ~/bashlab/backups
  keep: 7
  exclude:
    - "*.tmp"
    - ".cache/"
deploy:
  releases_dir: ~/bashlab/deploy/releases
  current_link: ~/bashlab/deploy/current
  keep_releases: 3
YAML

# ---------- 5) files/: deliberately created “odd names” ----------
f="$DATA_DIR/files"
# shellcheck disable=SC2016   # 'price $5.txt' : the $ is meant to stay literal
names=(
  'report 2026.txt'                 # space
  'two  spaces.txt'                 # two consecutive spaces
  $'tab\there.txt'                  # tab character
  $'line1\nline2.txt'               # newline
  '-n'                              # leading dash (treated as an option)
  '--verbose.log'                   # starts with two dashes
  '[draft] notes.md'                # brackets: glob characters
  'star*.txt'                       # asterisk
  'price $5.txt'                    # dollar sign
  "it's.txt"                        # single quote
  'say "hi".txt'                    # double quote
  'café-ünïcode.txt'                # non-ASCII (UTF-8)
  'trailing-space.txt '             # trailing space
  '.hidden.txt'                     # hidden file
  'sub dir/nested file.log'         # subdirectory with a space
)
k=0
for nm in "${names[@]}"; do
  k=$(( k + 1 ))
  printf 'file #%d\n' "$k" > "$f/$nm"
  touch -t "$(printf '2026111709%02d.00' "$k")" -- "$f/$nm"   # fixed modification times: 09:01, 09:02, ...
done
touch -t 202611170900.00 -- "$f/sub dir"

printf 'make-data.sh: generated %s\n' "$DATA_DIR"
printf '  access.log      %4d lines\n' "$(( $(wc -l < "$log") ))"
printf '  servers.csv     %4d lines (including header)\n' "$(( $(wc -l < "$csv") ))"
printf '  inventory.json  %4d objects\n' "$n"
printf '  config.yaml     opsctl sample config\n'
printf '  files/          %4d odd-named files\n' "${#names[@]}"
chmod +x ~/bashlab/make-data.sh
~/bashlab/make-data.sh
cd ~/bashlab/data && cksum access.log servers.csv inventory.json config.yaml
make-data.sh: generated /home/labadmin/bashlab/data
  access.log       611 lines
  servers.csv       13 lines (including header)
  inventory.json    12 objects
  config.yaml     opsctl sample config
  files/            15 odd-named files
80306651 79109 access.log
3087317886 526 servers.csv
3924293688 1199 inventory.json
1138550665 787 config.yaml

cksum (POSIX CRC + byte count) matches on Linux, macOS and BusyBox, so you can use it to confirm that your pasted script is intact. If the numbers differ, the most common causes are: CRLF was added while copying (use file make-data.sh to check whether it shows “with CRLF line terminators”), or the editor has ' automatically replaced straight quotes with curly quotes. The script can be run repeatedly; each run deletes and recreates data/.

Dataset overview (conventions used throughout the course)

FileContentsFacts worth remembering (used in later lessons)
access.log611 lines of nginx / gunicorn combined access log in that format, time 2026-11-17 10:00:01–10:31:00 (UTC); methods GET 524 / POST 87Line 1 is the spec example 203.0.113.7 … "GET /healthz HTTP/1.1" 200 2 "-" "curl/8.12.1"; status codes: 200×450, 201×54, 301×12, 302×19, 304×22, 400×11, 401×6, 404×9, 500×12, 502×4, 503×12 (5xx total 28 lines); paths /api/orders 211,/healthz 121,/ 75,/login 74,/api/orders/1042 67,/static/app.js 63; Lines 151–156: 198.51.100.23, 6 consecutive POST /login 401s (brute-force login); Line 307: the UA of 192.0.2.66 contains an apostrophe and nginx-escaped quotes \x22; Lines 458–461: 10.20.1.31, 4 consecutive 502s; the User-Agent strings all contain spaces
servers.csvHeader name,env,region,ip,role + 12 rows; env: dev 3 / staging 3 / prod 6; region: canadacentral,ca-central-1Line 11 edge-01,prod,ca-central-1,10.30.2.51,"web,api" contains a comma inside quotes —awk -F, / cut -d, would split it incorrectly (Lesson 5); name not unique (every environment has web-01), so the unique key is name+env
inventory.jsonthe same array of 12 objects as servers.csv, with the same field namesedge-01's "role": "web,api" is a plain string; Lesson 5 handles it with jq
config.yamlopsctl sample config: opsctl.*,environments.{dev,staging,prod},health,backup,deployLesson 3's opsctl reads its own etc/opsctl.conf (key-value format); this file is used for the Lesson 5 yq examples and the health / backup / deploy parameters in Lesson 6
files/15 “odd names”: spaces, consecutive spaces, tabs, newlines,-n,--verbose.log,[draft] notes.md,star*.txt,price $5.txt,it's.txt,say "hi".txt,café-ünïcode.txt, trailing space,.hidden.txt,sub dir/nested file.logwith contents file #1 … file #15, modification times 09:01 … 09:15 (sub dir is 09:00); files/* matches 14 items (13 files + 1 directory, excluding hidden files)

Environment self-check checklist

Risks and cleanup All deletion operations in this lesson (rm, overwriting redirections) are limited to ~/bashlab within ~/bashlab; the rm -rf commands shown in the examples only apply to ~/bashlab/tmp or ~/bashlab/data. Do not copy these into the home directory root or onto production servers. You can always ~/bashlab/make-data.sh rebuild the dataset; full cleanup: rm -rf -- ~/bashlab (Lessons 2–8 still use it, so keep it after finishing this lesson).

Module 1 · What Is a Shell: interactive vs script, startup files and shebang

00:00 – 06:00 · A shell is an ordinary program that “reads a line, interprets it, and asks the kernel to do the work”; how it is started determines which configuration files it reads and which variables and aliases it has
6 minBash 5.3 · POSIX sh comparison★★★★☆
Learning objectives
  • Distinguish terminal emulator, shell, kernel their roles, and know that /bin/sh on Ubuntu is dash rather than Bash.
  • Determine whether the current shell is interactive or non-interactive, login or non-login ($-,shopt login_shell,$0 the leading character of -).
  • Explain which startup files: /etc/profile → ~/.bash_profile | ~/.bash_login | ~/.profile; ~/.bashrc; BASH_ENV.
  • Understand shebang is handled by the kernel's execve parsing, and ./x.sh,bash x.sh,source x.sh — the essential differences among the three ways of running a script.
Prerequisites: Linux course Lesson 1 (processes, fork/execve). Importance:★★★★☆ (every “my alias/variable is missing in cron” problem comes from this)

What: terminal, shell and kernel

RoleWhat it isExamples
Terminal / terminal emulatordisplays characters and receives keyboard input, passing them via pseudo-terminal (pty) to the foreground processGNOME Terminal, Windows Terminal, iTerm2, SSH clients
ShellAn ordinary user-space program: reads command text → parses and expands it → executes (builtins run inside its own process; external commands use fork + execve) → collects the exit statusbash,dash,zsh,fish, BusyBox ash
Kernelthe place that actually creates processes, opens files and executes programs; the shell is just a high-level front end to system callsLinux 7.0 (Ubuntu 26.04)

Bash (Bourne-Again SHell) is the GNU project's shell, compatible with POSIX sh and adds arrays,[[ ]], process substitution, extended globbing and other features. Maintained by Chet Ramey; current major version 5.3 (2025-07), with official patches up to bash53-020.

Why: why distinguish how the shell was started

The same bash program behaves differently depending on how it was started: interactive shows a prompt, enables readline line editing and history, and expands aliases by default; non-interactive (running a script,bash -c, cron, CI) does not read ~/.bashrc, does not expand aliases by default, and job control is off. Many problems of the form “works when run by hand, fails in cron / CI / systemd” come from relying on things that exist only in an interactive shell (PATH additions, aliases, functions,nvm and similar initialization).

How: two dimensions, four combinations

Login shell (login)Non-login shell
InteractiveSSH login, console login,su -,sudo -i,bash -l, macOS Terminal new window
reads: /etc/profile, then ~/.bash_profile,~/.bash_login,~/.profile in the first existing and readable; on exit reads ~/.bash_logout
new tab in a Linux desktop terminal; typing bash,docker exec -it c bash
reads: ~/.bashrc (Bash builds from Debian/Ubuntu also read first /etc/bash.bashrc)
Non-interactiveRare: bash -l script.sh,bash -lc '…' (often used in CI to “simulate a login environment”)
reads: same as the login shell's profile series
./script.sh,bash script.sh,bash -c '…', cron, systemd, CI steps
reads: only $BASH_ENV points to (usually unset → reads nothing)

Two common “exceptions”: ① Ubuntu's default ~/.profile will source source ~/.bashrc, so you can also see .bashrc the aliases in ; ② Bash detects that it was started by sshd (or rshd) non-interactively (ssh host 'cmd'), it also reads ~/.bashrc— whereas the beginning of Ubuntu's ~/.bashrc has case $- in *i*) ;; *) return;; esac, which returns immediately when non-interactive. When started under the name sh , Bash enters POSIX mode: at login it reads /etc/profile and ~/.profile, and when interactive reads $ENV.

How: shebang is a kernel feature

When running ./deploy.sh , Bash calls execve("./deploy.sh", …). The kernel reads the beginning of the file, sees #! , treats the rest of the line as “interpreter path + at most one argument”, and instead runs /usr/bin/env bash ./deploy.sh. Therefore:

  • Linux splits the shebang only at the first whitespace into “interpreter” and “one optional argument”: #!/usr/bin/env bash -e will make env look for a program named bash -e and fail (the GNU / uutils env -S can split it, but not portably).
  • #!/bin/bash fixed path: most predictable; #!/usr/bin/env bash searches PATH for bash, more general on macOS + Homebrew, NixOS and containers. This course uniformly uses the latter (consistent with the opsctl convention).
  • When a file has no shebang,execve returns ENOEXEC, Bash will itself run it as a script in a subshell, so the file “runs without a shebang”, but if launched from Python subprocess or cron directly with exec, you get Exec format error.
  • CRLF line endings make the interpreter become bash\r: error /usr/bin/env: 'bash\r': No such file or directory.

When: three ways to run a script

MethodProcessNeeds x permission?shebang takes effect?Can the script change the current shell's variables / directory?
./deploy.shNew process (fork + execve)RequiredYesCannot
bash deploy.shNew process, interpreter specified explicitlyNot needed (only r)No (treated as a comment)Cannot
source deploy.sh / . deploy.shExecuted in the current shellNot neededNoCan— this is the principle behind source ~/.bashrc and . venv/bin/activate the . (dot) command

Bash vs other shells (selection comparison)

ShellPositioningSuited forNotes
bashGNU, POSIX superset, Linux default interactive shellops scripts, CI, container entry scriptsmacOS ships 3.2; slim container images may lack bash
dash (Ubuntu/Debian's /bin/sh)Small, fast POSIX shsystem startup scripts,#!/bin/sh portable scripts forno [[ ]], arrays,$'…' (newer dash 0.5.12+ supports $'…', but do not rely on it)
zshStrong interactive experience; default interactive shell on macOSpersonal terminalunquoted variables are, by default,not word-split, array indices start at 1, and are incompatible with bash scripts
BusyBox ashAlpine image's /bin/shvery small imagessupports only some bash extensions
Common misconceptions① “#!/bin/sh is bash”—on Ubuntu/Debian it is dash, on Alpine it is BusyBox; writing bash syntax means you must use a bash shebang. ② “.bashrc applies to every bash”—non-interactive shells do not read it. ③ “$SHELL is the current shell”—it is only the path of the login shell. ④ “Adding a shebang and invoking with bash x.sh still follows the shebang”—when the interpreter is named explicitly, the shebang is just a comment line. ⑤ “export Putting .bashrc in it, cron will see it”—cron uses by default /bin/sh, and does not read it at all.

Architecture diagram: from keyboard to kernel

Terminal emulatorWindows Terminal / iTerm2or SSH client keystrokes pty/dev/pts/0line discipline · signal keys fd 0 bash (interactive) readline: editing, history, completion parse → expand → redirect → look up command builtins: cd · export · echo · read (in this process) external: fork → child process execve child processls / grep / pythonfd 1/2 → pty Linux kernel clone / execve (parses #! line, checks x permission) / openat / dup2 / pipe / wait4 / kill pty driver turns Ctrl+C into SIGINT sent to the foreground process group · process exit status passed to parent → $? The shell is just an ordinary program: everything it does is done through these system calls
Figure 1-1: the terminal only displays and takes input; the shell interprets commands; the kernel is what actually creates processes and runs programs

Flowchart: which files Bash reads at startup

bash starts Login shell? (-l / argv[0] starts with -) Yes /etc/profile then reads the first that exists, in order: ~/.bash_profile → ~/.bash_login → ~/.profile (Ubuntu's ~/.profile then sources ~/.bashrc) No Interactive? ($- contains i) Yes No /etc/bash.bashrc (Debian family)~/.bashrc--norc skips it reads only $BASH_ENVscript · bash -c · cronCI · systemd On logout from login shell: ~/.bash_logout--noprofile skips the profile seriesStarted as sh: /etc/profile, ~/.profile, $ENV
Figure 1-2: first decide “login”, then decide “interactive”; a non-interactive, non-login shell reads no config at all (unless BASH_ENV is set)

Startup file read simulator

Choose a startup method and step through how Bash works out its type and which files it reads, and whether you can use ~/.bashrc the aliases defined in ll and ~/.profile the entries added to PATH=$HOME/bashlab/bin:$PATH.

Ready.
Real mechanisms behind the animation Bash in shell.c the startup flow, a login shell is identified by argv[0] whether its name starts with - (or -l/--login), and interactivity is determined by whether stdin and stderr are both connected to a terminal and no script or -c command string was given (or -i), then files are read in the order described in the Bash Startup Files section of the manual. login,sshd,su - exactly by setting argv[0] to -bash request a login shell, so in a login shell you echo $0 can see -bash.

Command table

CommandPurposeNotes
echo $-Current shell option flagsContains i = interactive; h hash,B brace expansion,m job control,H history expansion
shopt login_shellWhether it is a login shell (read-only option)shopt -q login_shell && echo login
echo $0Name of the shell or scriptLogin shell shows -bash
bash -l / -i / -cforce login / interactive / command stringbash -c 'cmd' name arg1: name becomes $0
bash --norc / --noprofileskips ~/.bashrc / profile seriescheck whether it is a configuration-file problem
env -i bash --norc --noprofilefully clean environmentreproduce the minimal environment of cron / systemd
source file / . filerun a file in the current shellNew in 5.3 source -p PATH file: look up in the given path
readlink -f /bin/shcheck what sh actually isUbuntu: /usr/bin/dash
echo "\$-=$-  \$0=$0"
shopt login_shell
bash -c 'echo "in bash -c: \$-=$-"; shopt -q login_shell && echo login || echo non-login'
readlink -f /bin/sh
$-=himBHs  $0=-bash
login_shell    	on
in bash -c: $-=hBc
non-login
/usr/bin/dash

How to verify:$- contains i means interactive; bash -c the $- with c (since 5.x) and no i. Common mistake: Using [[ $- == *i* ]] other than this (e.g. checking $PS1) to determine interactivity —PS1 may be inherited. Production use: At the top of ~/.bashrc for non-interactive shells, directly return, avoid scp/rsync failing because of welcome output.

# bash -c positional parameters: the first extra argument becomes $0
bash -c 'echo "0=$0 1=$1 #=$#"' myname a b
# Simulate cron's minimal environment
env -i HOME="$HOME" PATH=/usr/bin:/bin bash --noprofile --norc -c 'echo "PATH=$PATH"; type ll 2>&1'
0=myname 1=a #=2
PATH=/usr/bin:/bin
bash: line 1: type: ll: not found
# Differences among the three ways to run a script
cd ~/bashlab/scripts
printf '#!/usr/bin/env bash\ncd /tmp\nGREETING=hello\necho "script pid=$$ cwd=$PWD"\n' > where.sh
bash where.sh;   echo "after bash:   cwd=$PWD GREETING=${GREETING-unset}"
source where.sh; echo "after source: cwd=$PWD GREETING=${GREETING-unset}"
cd ~/bashlab/scripts
script pid=48211 cwd=/tmp
after bash:   cwd=/home/labadmin/bashlab/scripts GREETING=unset
script pid=47002 cwd=/tmp
after source: cwd=/tmp GREETING=hello

source When $$ is the current interactive shell's PID; the directory and variables have been changed. ${GREETING-unset} is the default-value syntax for parameter expansion (covered in detail in Lesson 2).

Goal: Verify by hand which startup files each of the four shell combinations reads. Environment: Any Bash 5.x; only modify ~/bashlab files under it, and use HOME variable to temporarily point the “home directory” at a sandbox,without touching your real ~/.bashrc. Cost: None.

Prepare the sandbox home directory: each startup file writes one line to the log when it is read.
sandbox=~/bashlab/tmp/fakehome
mkdir -p "$sandbox"
for f in .bash_profile .bash_login .profile .bashrc .bash_logout; do
  printf 'echo "read %s" >> "$HOME/startup.log"\n' "$f" > "$sandbox/$f"
done
printf 'echo "read BASH_ENV file" >> "$HOME/startup.log"\n' > "$sandbox/env.sh"
ls -A "$sandbox"
.bash_login  .bash_logout  .bash_profile  .bashrc  env.sh  .profile
Test the four combinations one by one (-i force interactive,-l force login; </dev/null make the interactive shell exit immediately on reaching EOF):
run() { : > "$sandbox/startup.log"; HOME="$sandbox" "$@" </dev/null >/dev/null 2>&1; printf '%-28s → %s\n' "$*" "$(paste -sd, "$sandbox/startup.log")"; }
run bash -l -i
run bash -i
run bash -l -c true
run bash -c true
BASH_ENV="$sandbox/env.sh" run bash -c true
bash -l -i                   → read .bash_profile,read .bash_logout
bash -i                      → read .bashrc
bash -l -c true              → read .bash_profile
bash -c true                 →
bash -c true                 → read BASH_ENV file

Note: the login shell only read .bash_profile— because it exists,.bash_login and .profile were skipped. This is the usual cause of “the PATH I wrote in ~/.profile does not take effect”: some tool (such as an installer script) created ~/.bash_profile. /etc/profile was also read, but it does not write to our log. .bash_logout is read when an interactive login shell exits.

Delete .bash_profile, then check the login shell:
rm "$sandbox/.bash_profile"; run bash -l -c true
rm "$sandbox/.bash_login";   run bash -l -c true
bash -l -c true              → read .bash_login
bash -l -c true              → read .profile
Verify that the kernel handles the shebang:
cd ~/bashlab/scripts
printf '#!/usr/bin/env bash -e\necho hi\n' > bad-shebang.sh && chmod +x bad-shebang.sh
./bad-shebang.sh; echo "rc=$?"
printf 'echo "no shebang, run by: $BASH_VERSION"\n' > noshebang.sh && chmod +x noshebang.sh
./noshebang.sh
/usr/bin/env: 'bash -e': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
rc=127
no shebang, run by: 5.3.3(1)-release

First script: the kernel passes bash -e as a single argument to env. Second script: the kernel returns ENOEXEC, and Bash itself takes over and runs it.

Cleanup: rm -rf -- ~/bashlab/tmp/fakehome ~/bashlab/scripts/{bad-shebang,noshebang,where}.sh

Case 1: “nvm: command not found” in CI

Problem: On the dev machine, nvm use 22 works, but the step on a self-hosted GitHub Actions runner fails with 127. Root cause: nvm is loaded in ~/.bashrc as a shell function, CI steps run non-interactively bash -e {0} and do not read .bashrc. Fix: explicitly source it in the step source "$NVM_DIR/nvm.sh", or switch to a tool that does not depend on shell initialization (the official setup-node action, or use the binary path directly). Caveat: Using bash -l can also “fix” it, but it brings in other side effects from the profile, so CI results come to depend on machine configuration.

Case 2: scp / rsync suddenly fails

Problem: Someone added ~/.bashrc at the end of echo "Welcome to prod!", after which scp reports “protocol error” or rsync reports “protocol version mismatch”. Root cause: When sshd starts bash non-interactively, it still reads ~/.bashrc, so the welcome text gets mixed into the protocol stream. Fix: At the top of .bashrc keep [[ $- == *i* ]] || return, put output-producing content after it, or put it in /etc/motd.

Case 3: #!/bin/sh a script reports “Bad substitution” on Ubuntu

Problem: A script that tests fine on macOS / RHEL reports Syntax error: "(" unexpected or Bad substitution. Root cause: RHEL's /bin/sh is bash, while Ubuntu's is dash; the script uses arrays and ${var//a/b}. Fix: If it uses Bash features, write #!/usr/bin/env bash; when POSIX portability is needed, use checkbashisms or ShellCheck's --shell=sh check (Lesson 7).

Common errors and fixes

/usr/bin/env: 'bash\r': No such file or directory

Cause: The script was saved with CRLF (Windows) line endings, so the kernel reads the interpreter name as bash\r.

file deploy.sh                 # “with CRLF line terminators”
head -n1 deploy.sh | od -c | head -n2

Fix:sed -i 's/\r$//' deploy.sh (macOS: sed -i '' …) or dos2unix; add to the repository .gitattributes: *.sh text eol=lf.

Aliases / functions defined in ~/.bashrc give “command not found” in scripts or cron

Cause: Non-interactive shells do not read ~/.bashrc; even if they did, aliases are not expanded by default in non-interactive shells.

bash -c 'type ll'                       # not found
bash -ic 'type ll' 2>/dev/null          # only exists interactively

Fix: Do not depend on aliases in scripts; put needed functions into a separate file and explicitly source; set PATH explicitly at the top of the script.

Changed ~/.profile, but after reopening the terminal PATH is still the old one

Cause:① existence of ~/.bash_profile (or .bash_login),.profile means it is skipped; ② desktop terminals open a non-login shell,.profile which reads it only once, at graphical login.

ls -l ~/.bash_profile ~/.bash_login ~/.profile 2>&1
shopt login_shell

Fix: keep one profile file; in ~/.bash_profile add [[ -f ~/.profile ]] && . ~/.profile; or log out and log back in to the desktop session.

sh: 1: [[: not found / Syntax error: "(" unexpected

Cause: The script was run by dash: its shebang is #!/bin/sh, or it was run with sh script.sh .

head -n1 script.sh; readlink -f /bin/sh

Fix: Change the shebang to #!/usr/bin/env bash and run it with ./script.sh or bash script.sh .

Command-line exercises
1. Write one command line that prints both whether the shell is interactive and whether it is a login shell.
[[ $- == *i* ]] && i=interactive || i=non-interactive; shopt -q login_shell && l=login || l=non-login; echo "$i / $l"

Running directly in a terminal and running from bash -c '…' give different results.

2. Without modifying any files, start an interactive Bash that reads no personal configuration.
bash --noprofile --norc

Then add env -i to also clear the environment variables: env -i TERM="$TERM" HOME="$HOME" PATH=/usr/bin:/bin bash --noprofile --norc (you must give PATH or write /bin/bash the absolute path, otherwise env itself cannot find bash: env: 'bash': No such file or directory).

Scenario analysis
An ops colleague says: “I put ~/.bashrc in export AWS_PROFILE=prod, and the backup script works when run by hand, but the cron backup uploads to the default account.” Analyze and propose a fix.

cron starts a non-interactive, non-login shell (and by default it is /bin/sh), so it does not read ~/.bashrc, so AWS_PROFILE is not set, and the CLI falls back to default credentials — this is a silent error that is more dangerous than an error message. Fix: ① explicitly set and validate it inside the script: : "${AWS_PROFILE:?must be set}"; ② write in the crontab AWS_PROFILE=prod or prefix the assignment at invocation; ③ better: use a systemd timer and declare it in the unit Environment=. Principle: A script's runtime environment must be self-contained, and must not depend on interactive configuration files.

Verified teaching videos

▶
Bash in 100 Seconds — Fireship
English · about 2 min · quick overview of what Bash is, shebang and scripts
▶
Beginner's Guide to the Bash Terminal — Joe Collins (EzeeLinux)
English · getting started with interactive Bash

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration script are provided for a video tool to produce it.

Shot 1 · 0–15s
Visual: keyboard → terminal window → a box labeled bash → the kernel below.
Narration: the terminal only displays; Bash interprets your commands; the kernel does the real work.
Shot 2 · 15–45s
Visual: a 2×2 table lights up: login/non-login × interactive/non-interactive; each cell pops up its file names.
Narration: the same Bash reads different configuration files depending on how it starts. Scripts and cron read nothing.
Shot 3 · 45–70s
Visual: ./deploy.sh Enters the kernel, which reads #!/usr/bin/env bash, and runs env instead.
Narration: shebang is a kernel feature; it only recognizes one interpreter plus one argument.
Shot 4 · 70–90s
Visual: three columns compare ./x.sh, bash x.sh, source x.sh; only source changes the current directory.
Narration: to change the current shell, use source; the other two both run in a new process.
or score ≥ 70% on the Quiz

Module 2 · Types of Commands: builtins, keywords, functions, aliases and external commands

06:00 – 13:00 · The “command name” you type may refer to five completely different things; Bash determines which one it is at different stages, in a fixed order
7 minBash 5.3★★★★☆
Learning objectives
  • Name the five kinds of commands: alias (alias), keyword (keyword), function (function), builtin (builtin), external command (file), and the first two are recognized in the parsing stage, the last three in the execution stage.
  • Remember the lookup order at execution time: function → builtin → hash table → $PATH; names containing a slash skip the lookup.
  • Be proficient with type -a,type -t,command -v,command,builtin,\name,hash, and know why which is unreliable.
  • Understand cd,export,read why must be a builtin,[[ why it is a keyword, while [ is a builtin.
Prerequisites: Module 1. Importance:★★★★☆

What: five kinds of commands

TypeDefinitionExampleWhen recognizedtype -t
Alias (alias)Text substitution: replaces a word in command position with a piece of textalias ll='ls -l'At read / tokenization timealias
Keyword (keyword)Part of shell syntax (reserved word)if then fi for while case [[ ]] { } ! time function coprocAt parse timekeyword
Function (function)A group of commands defined in the current shellgreet() { echo hi; }At execution time, priority 1function
Builtin (builtin)Commands compiled into bash, run inside the shell process (about 60)cd export read echo printf test [ source exit type hashAt execution time, priority 2builtin
External command (file)Executable file on disk, requires fork + execve/usr/bin/ls,/usr/bin/grep, your scriptAt execution time, look up the hash table, then PATHfile

Why: why some commands must be builtins

  • Change the shell's own state: working directory (cd,pushd), variables (export,read,declare,local), options (set,shopt), control flow (exit,return,break), reading files (source), file descriptors (exec). If they were external programs, the changes would only happen in a child process and disappear with it.
  • Performance: echo,printf,test/[,true/false,kill External versions also exist (/usr/bin/printf), but the builtin version avoids the fork + execve. In a loop running 10,000 times, the difference can be tens of times.
  • Keywords are syntax: [[ $f == *.log ]] Inside $f undergoes no word splitting or pathname expansion, and == the right-hand side is a pattern. This works only because the parser knows at parse time that “this is [[ syntax”. Whereas [ is just an ordinary command named [ , and its arguments are expanded as usual, so [ $f = x ] it fails when $f is empty or contains spaces.

How: the full order in which Bash decides “what this is”

  1. Aliases: when a line is read and tokenized, if the word in command position is unquoted and matches an alias, it is replaced by the alias text (if the alias value ends with a space, the next word is also checked for aliases). Non-interactive shells do not expand aliases by default (shopt -s expand_aliases can be turned on).
  2. Keywords: the parser recognizes reserved words and builds if/for/[[ ]] and other compound commands.
  3. After expansion and redirection, if the command name contains no slash, look up in this order: Function → Builtin → Hash table (remembered full paths) → search $PATH from left to right for an executable (recording it in the hash table).
  4. If nothing is found: if a command_not_found_handle function is defined, it is called (Ubuntu uses it to print a “can be installed with apt install …” hint); otherwise, report command not found, exit status 127.
  5. If the command name contains a slash (./run.sh,/usr/bin/ls): no lookup is done; the given path is executed directly.

In POSIX mode, “special builtins” (break : . continue eval exec exit export readonly return set shift trap unset) take precedence over functions; in default mode, a function can override any builtin, including cd (many people wrap cd).

When: how to bypass a given layer

SyntaxBypassesExample
\ls or 'ls'bypasses only aliases (quoting makes it no longer an “unquoted word”): functions still apply.\rm file Skips alias rm='rm -i'
command lsbypasses aliases and functions, looks up builtins and PATHFunction ls() { command ls --color=auto "$@"; }
builtin cdBuiltins onlywrapper function cd() { builtin cd "$@" && ls; }
/usr/bin/printf or env printfforce an external commandcompare builtin vs external behavior
enable -n echoDisable a builtin in the current shellRarely used, mainly for testing

Comparison: type, command -v, which

ToolTypeKnows about aliases/functions/builtins?Recommendation
type -a nameBash builtinKnows all of them and lists all candidatesPreferred for interactive troubleshooting
command -v namePOSIX builtinKnows it; prints the path or name, returns non-zero if not foundThe standard way to check dependencies in scripts: command -v jq >/dev/null || util::die …
which nameExternal programDoesn't know (it is a child process and can't see shell internals)Don't use in scripts; implementations differ across distributions
Common misconceptions① “\cmd can bypass functions”—a backslash only bypasses aliases; to bypass functions, use command. ② “echo is /usr/bin/echo”—in Bash, prefer the builtin echo, the two handle -e,-n not always the same. ③ “a newly installed version is used immediately”—the hash table may still remember the old path; run hash -r to clear it. ④ “which says it isn't found means it doesn't exist”—cd,ll such builtins or aliases which can never be found. ⑤ “[ and [[ are the same”—one is an ordinary builtin, the other is a keyword, with different quoting and expansion rules (see Lesson 2).

Architecture diagram: where the five kinds of commands live

Inside the bash process (no fork) Alias tablell → ls -ltext substitution at tokenization Keywords (syntax)if for [[ ]] { } timerecognized at parse time Function tablegreet() { … }at execution, ① first Builtins (compiled into bash)cd export read echo printf [ … ② first Hash table (path cache)ls → /usr/bin/ls … ③ Disk: directories in $PATH ④ /home/labadmin/bashlab/bin /usr/local/sbin · /usr/local/bin /usr/sbin · /usr/bin /sbin · /bin (mostly links to /usr) Found → fork + execve (new process) Not found → command_not_found_handle / 127 Command name contains “/” (./run.sh, /usr/bin/ls) → skip ①–④, run the path directlyno execute (x) permission → 126; file doesn't exist → 127 (No such file or directory)
Figure 2-1: aliases and keywords are handled at parse time; functions, builtins, hash table and PATH are looked up in order at execution time

Flowchart: command lookup at execution time

Command name(after expansion) Contains /?Yes → run directly ① Function?declare -F ② Builtin?enable -a ③ Hash table?hash ④ PATH searchleft to right 127not found Run in the current shellRun in the current shell fork → child process (redirection) → execve “Run in the current shell” has exceptions: when in a pipeline, inside ( ), or backgrounded with &, functions and builtins also run in a subshell (Modules 6, 7). The hash table is cleared automatically when PATH changes; manually: hash -r; shopt -s checkhash makes bash verify the hashed path still exists before executing it
Figure 2-2: functions → builtins → hash → PATH; the first two don't fork, the last two fork + execve

Command lookup resolver

Current shell state: aliases ll='ls -l',rm='rm -i'; functions greet,ls (wrapper function ls() { command ls --color=auto "$@"; }); hash table remembers grep → /usr/bin/grep; PATH=/home/labadmin/bashlab/bin:/usr/local/bin:/usr/bin:/bin. Select a command line and step through Bash's decision at each layer.

Ready.
The real mechanism behind the animation Alias substitution happens when the lexer reads the word in command position (Bash source parse.y in alias_expand_token); keywords are recognized by the parser; when executing a simple command, execute_cmd.c functions are checked first (find_function), then builtins (find_shell_builtin), and finally search_for_command the hash table and PATH are checked. Green = matched and executed, yellow = checked, continue, red = failed.

Command reference

CommandPurposeKey options
type -a nameList every identity of name-t Print only the type; -P search PATH only; -f ignore functions
command -v nameCheck whether a command exists in scripts-V Print descriptive text
alias / unaliasView / define / remove aliasesalias With no arguments, lists all; unalias -a
declare -F / declare -f nameList function names / print a function's definitionunset -f name Remove a function
enable -a / compgen -bList builtinsenable -n x Disable
compgen -kList keywordscompgen -a aliases,-A function functions
hash / hash -rView / clear the command path cachehash -d name Remove one entry
help nameHelp for builtins and keywordshelp -d cd one-line description; for external commands, use man
shopt -s expand_aliases            # needed when demonstrating aliases in a script; can be omitted in an interactive terminal
alias ll='ls -l'
greet() { echo hi; }
type -t cd echo if ll greet ls '[' '[[' time printf
builtin
builtin
keyword
alias
function
file
builtin
keyword
keyword
builtin
type -a echo
compgen -k | tr '\n' ' '; echo
echo is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo
if then else elif fi case esac for select while until do done in function time { } ! [[ ]] coproc 

How to verify:type -a 's first line is the one Bash actually executes. Common mistakes: Treating type 's output as a machine-readable format; in scripts, use type -t or command -v. Production use: Troubleshooting why the same command behaves differently on different machines.

# \name only bypasses aliases, not functions; command bypasses both
echo() { builtin echo "[fn] $*"; }
echo hi; command echo hi2; \echo hi3
unset -f echo
[fn] hi
hi2
[fn] hi3
# standard way to check dependencies in scripts (used by opsctl's util::require_cmd)
for c in jq curl awk; do
  if command -v "$c" >/dev/null 2>&1; then printf '%-5s ok (%s)\n' "$c" "$(command -v "$c")"
  else printf '%-5s MISSING\n' "$c"; fi
done
jq    ok (/usr/bin/jq)
curl  ok (/usr/bin/curl)
awk   ok (/usr/bin/awk)
# Hash table: what happens when an old path is remembered
mkdir -p ~/bashlab/tmp/h1 ~/bashlab/tmp/h2
printf '#!/usr/bin/env bash\necho "v1"\n' > ~/bashlab/tmp/h1/foo && chmod +x ~/bashlab/tmp/h1/foo
PATH="$HOME/bashlab/tmp/h2:$HOME/bashlab/tmp/h1:$PATH"
foo; hash | grep foo
mv ~/bashlab/tmp/h1/foo ~/bashlab/tmp/h2/foo
foo; echo "rc=$?"
hash -r; foo
v1
   1	/home/labadmin/bashlab/tmp/h1/foo
bash: /home/labadmin/bashlab/tmp/h1/foo: No such file or directory
rc=127
v1

When PATH is reassigned, Bash automatically clears the hash table, so the first foo lookup goes through PATH search; after the file is moved, the hash table still points to the old path until hash -r. After the experiment, a new terminal restores PATH, or rm -rf -- ~/bashlab/tmp/h1 ~/bashlab/tmp/h2.

Goal: Make the same name datainfo successively become an external command, a function, and an alias, observing precedence; and measure the performance gap between the builtin and external printf versions. Environment: Any Bash 5.x,~/bashlab. Cost: None.

External command: in ~/bashlab/bin , put a script and add it to PATH (Module 8 turns it into a proper tool).
cat > ~/bashlab/bin/datainfo <<'EOF'
#!/usr/bin/env bash
echo "[file] datainfo: $# args"
EOF
chmod +x ~/bashlab/bin/datainfo
export PATH="$HOME/bashlab/bin:$PATH"
datainfo a b; type -a datainfo
[file] datainfo: 2 args
datainfo is /home/labadmin/bashlab/bin/datainfo
Define a function with the same name: functions take precedence over PATH.
datainfo() { echo "[function] datainfo: $# args"; }
datainfo a b; type -a datainfo | head -n1
command datainfo a b              # bypasses the function
[function] datainfo: 2 args
datainfo is a function
[file] datainfo: 2 args
Then define an alias with the same name (in an interactive terminal): the alias is substituted first.
alias datainfo='echo "[alias] datainfo"'
datainfo a b
\datainfo a b                     # bypasses the alias → function
unalias datainfo; unset -f datainfo
datainfo a b
[alias] datainfo a b
[function] datainfo: 2 args
[file] datainfo: 2 args

An alias is just text substitution: datainfo a b becomes echo "[alias] datainfo" a b, so a b is printed by echo. unalias must be on its own line: Bash reads a full line and expands aliases before running it; if written as unalias datainfo; …; datainfo a b, the datainfo on the same line is still expanded as an alias.

Builtin vs external performance:
time (for i in {1..2000}; do printf '%s' x >/dev/null; done)
time (for i in {1..2000}; do /usr/bin/printf '%s' x >/dev/null; done)
real	0m0.012s
...
real	0m1.734s
...

2000 calls of fork + execve typically cost hundreds of times more than the builtin version, which is why Lesson 5 stresses “don't call external commands line by line in a loop; use a single awk instead.”

Cleanup: keep ~/bashlab/bin/datainfo (Module 8 will rewrite it); hash -r.

Case 1: alias rm='rm -i' gives a false sense of safety

Problem: A team, in the /etc/bash.bashrc of every server, set alias rm='rm -i', believing it prevents accidental deletion; in ops scripts, the rm -rf "$DIR/"* instead, when DIR was empty, deleted files under the root directory. Root cause: The script is non-interactive, so the alias never took effect; the real problem is the variable being empty. Fix: In scripts, use rm -rf -- "${DIR:?}/"* (exits with an error if empty; Lesson 2) and strict mode (Lesson 4); for interactive protection, use trash-cli and similar tools.

Case 2: still running the old tool version after an upgrade

Problem: In a long-running tmux session, running kubectl reports “No such file or directory”, but ls /usr/local/bin/kubectl clearly exists. Root cause: The upgrade script moved kubectl from /usr/bin to /usr/local/bin, but Bash's hash table still remembers the old path. Fix:hash -r; in the team's .bashrc file, enable shopt -s checkhash. Limitation: Only affects shells that are already open; new terminals don't have this problem.

Case 3: which causes a false alarm in dependency detection

Problem: The install script uses if [ -z "$(which docker)" ] to check dependencies; on some minimal images which itself is missing, so the script wrongly concludes “docker is not installed” and tries to reinstall it. Fix: Switch everything to command -v docker >/dev/null 2>&1; it is a POSIX-specified shell builtin that depends on no external package. This is exactly how opsctl does it in util::require_cmd 's implementation (exit code 3 means a missing dependency).

Common errors and fixes

bash: foo: command not found (exit code 127)

Cause: a typo, not installed, directory not in PATH, or in sudo , PATH is replaced by secure_path .

type -a foo; printf '%s\n' "${PATH//:/$'\n'}"
sudo sh -c 'echo "$PATH"'

Fix: install the software, use an absolute path, or add the directory to PATH (interactively, put it in ~/.profile, and in scripts, set it explicitly at the top).

bash: /usr/bin/kubectl: No such file or directory (the file was moved elsewhere)

Cause: The old path is still in the hash table.

hash | grep kubectl; type -a kubectl

Fix:hash -r or hash -d kubectl.

alias has no effect in scripts: line 3: ll: command not found

Cause: Non-interactive shells do not expand aliases by default; also, aliases are processed when the input is read, so defining and using one on the same line (or within the same compound command) does not work.

bash -c 'alias ll="ls -l"; ll'                      # fails
bash -c 'shopt -s expand_aliases
alias ll="ls -l"
ll -d /tmp'                                         # works: definition and use are on different lines

Fix: In scripts, use a function instead of an alias: ll() { ls -l "$@"; }.

bash: syntax error near unexpected token `(' (when defining a function)

Cause: the function name is the same as an existing alias: ls() { …; } in the ls is first expanded by the alias into ls --color=auto, causing a syntax error.

alias ls; type -a ls

Fix: first unalias ls, or use function ls { …; } syntax (function the word after a keyword is not alias-expanded), but as long as the alias still exists, the later-typed ls is still substituted by the alias first,type -t ls shows alias (verified on Bash 5.2).

Command-line task
1. Write a function cd: that automatically displays ls after every directory change, and preserves cd's exit code on failure.
cd() { builtin cd "$@" && ls; }

must use builtin cd, otherwise the function would call itself and recurse forever. && Make sure ls does not run if cd fails, so the function's exit code is cd's exit code.

2. List all executables in PATH named python3 executable files (not affected by aliases or functions).
type -aP python3

-P Force a PATH-only search with -a and list all matches.

Scenario analysis question
A colleague's script contains [ $env == prod ] && echo "careful", and when env is empty, it reports [: ==: unary operator expected, and changing it to [[ $env == prod ]] fixes it. Explain why, from the “command type” perspective.

[ is a builtin command (there is also an external version /usr/bin/[), and its arguments are already normally expanded before execution: $env is empty and unquoted, so after expansion it is removed by word splitting,[ so the arguments it receives are == prod ], a syntax error. [[ is a keyword, handled by the parser; variables inside it undergo no word splitting or pathname expansion, so even empty values compare correctly. Correct forms: [ "$env" = prod ] (POSIX) or [[ $env == prod ]] (Bash). Also == in POSIX [ is not a standard operator; use =.

Verified teaching videos

▶
Lecture 1: Course Overview + The Shell (2020) — Missing Semester
English · MIT “The Missing Semester of Your CS Education” Lecture 1: Shell, PATH, which, programs and arguments
▶
Bash Scripting Tutorial for Beginners — freeCodeCamp.org
English · full introductory course; commands, aliases and script basics

No verified video specifically covering the “function → builtin → hash → PATH lookup order” was found; refer to this module's animation and storyboard script.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided, which can be given to a video tool to generate.

Shot 1 · 0–20s
Visual: the same word “ls” wears five hats: alias, keyword, function, builtin, file.
Narration: the command name you type could be five different things.
Shot 2 · 20–50s
Visual: a conveyor belt; the word first passes the “alias substitution” and “syntax recognition” stations, then enters four gates: function, builtin, hash, PATH.
Narration: aliases and keywords are handled at parse time; functions, builtins, the hash table and PATH are looked up in order at execution time.
Shot 3 · 50–75s
Visual: if cd were an external program, the child process changes directory and then vanishes, while the parent shell stays put.
Narration: commands that change the shell's own state must be builtins.
Shot 4 · 75–90s
Visual: the terminal shows type -a, command -v and hash -r typed in turn.
Narration: use type to investigate identity, command dash v to detect in scripts, and hash dash r when a path is stale.
or score ≥ 70% on the “Quiz”

Module 3 · Quoting: single quotes, double quotes, $'…' and escaping

13:00 – 21:00 · Quoting decides two things: which characters lose their special meaning, and whether the expansion result gets split again. 90% of Bash bugs are “a missing pair of double quotes”
8 minutesBash 5.3 · POSIXThe most frequent source of bugs★★★★★
Learning objectives
  • State precisely the rules for the four quoting methods: backslash, single quotes '…', double quotes "…", ANSI-C quoting $'…' (and the rarely used $"…" localized strings).
  • Understand that “quotes are part of the word”: "a"'b'c is a word; quotes are kept until the last step quote removal , when they are removed.
  • Build the default habit: Every $var,$(cmd), and "${arr[@]}" all get double quotes, and know the few places where quotes can be omitted.
  • Use printf '%q',${var@Q} and -- to safely display and pass ~/bashlab/data/files/ filenames with odd characters in
Prerequisites: Module 2. Importance:★★★★★

What: four quoting methods

SyntaxWhich characters remain special insideIs the result subject to word splitting / globbing?Typical use
Backslash \cProtects only the immediately following one character; a trailing \ + newline = line continuation (both are removed)—rm my\ file, for wrapping long commands
Single quotes '…'have no: everything is literal, even \ is an ordinary character; so inside single quotes cannot contain a single quoteNoregular expressions, awk / jq / sed programs, any “as-is” string
Double quotes "…"$ (parameter, arithmetic, command substitution),`,\ (only when followed by $ ` " \ or a newline); interactively, history expansion !No; this is why double quotes are neededAll variable and command substitutions: "$f","$(date +%F)"
ANSI-C $'…'Backslash escapes: \n \t \\ \' \" \xHH \uHHHH \e \0NNNNoTabs, newlines, the single quote itself: IFS=$'\n',$'it\'s'
$"…"Same as double quotes, and translated per the current locale (gettext)NoLocalized messages, rarely used in ops scripts

Why: quoting controls both “special characters” and “later steps”

In the expansion order of Module 4, after parameter expansion and command substitution there are two more steps: Word splitting (split by IFS characters: spaces, tabs and newlines) and pathname expansion (* ? […] matching files). These two steps apply only to unquoted expansion results. So:

f='report 2026.txt'
rm $f        # rm gets two arguments: report and 2026.txt  → wrong file deleted / error
rm "$f"      # rm gets one argument: report 2026.txt       → correct
x='*'
echo $x      # expands to all filenames in the current directory!
echo "$x"    # just a literal *

How: quotes are part of a “word”

  • A word can be built from several concatenated pieces: "$HOME"/'my dir'/$'tab\there' is one word, with each piece following its own rules.
  • To put a single quote inside a single-quoted string: end the single quote, add an escaped single quote, then start again: 'it'\''s'; or use "it's",$'it\'s'.
  • Inside command substitution is a new quoting context: "$(grep "$pat" "$file")" the inner and outer quotes do not interfere with each other, and this is the main reason $( ) is easier to use than backticks `…` .
  • Quotes are removed only in the final step (quote removal); quote characters in the text produced by expansion are not treated as quotes again: v='"a b"'; printf '<%s>' $v gives <"a><b">. To parse a “quoted string” as a command, you need eval; but that is almost always the wrong approach (use an array instead, Lesson 2).

When: when you can omit double quotes

LocationIs quoting needed?Reason
Ordinary command arguments cmd $xYesSubject to word splitting and globbing
Right side of assignment y=$x,y=$(cmd)Can be omitted (harmless if added)Assignments undergo no word splitting or pathname expansion
[[ $x == … ]] Left sideCan be omitted[[ is a keyword with no splitting inside; but right side unquoted is pattern matching; quoted is a literal comparison
case $x inCan be omittedThe case word is not split
$(( x + 1 ))Not neededArithmetic context
Arrays "${arr[@]}", positional parameters "$@"must be quoted(when quoted, each element becomes exactly one word; Lesson 2).
Intentionally split: opts='-l -a'; ls $optsUnquotedworks but is fragile; arrays are recommended opts=(-l -a); ls "${opts[@]}"
Common misconceptions① “can use \'”—no; inside single quotes, a backslash has no special meaning; 'it\'s' in fact it is 'it\' + s'…, and the quotes are misaligned from then on, so the rest of the line is parsed incorrectly (the author hit this once while writing this lesson). ② “double quotes prevent all expansion”—$ and ` still expand inside double quotes. ③ “echo $var shows the variable's real contents”—by then it has already been split, globbed, and had multiple spaces collapsed into one; use printf '%q\n' "$var" or declare -p var. ④ “filenames never contain newlines”—on Linux, only / and NUL are disallowed; see files/. ⑤ “adding quotes "*.txt" can match txt files”—with quotes it is a literal asterisk; the wildcard must be outside the quotes: "$dir"/*.txt.

Special characters across the four kinds of quotes

Character → Space/Tab* ? [$`\' itself" itself! (interactive) Unquoted Splits words Globbing Expansion + splitting Command substitution Escape Starts quoting Starts quoting History expansion "Double quotes" Literal Literal Expands · no split Command substitution Only $`"\↵ before Literal Ends quoting still expands 'Single quotes' Literal Literal Literal Literal Literal Ends quoting Literal Literal $'ANSI-C' Literal Literal Literal Literal \n \t \x41 \' available Literal Literal Red = has special meaning; yellow = partly special (expanded inside double quotes, but the result is no longer split or globbed); green = ordinary character; blue = escape sequence
Figure 3-1: single quotes are the “safest”; double quotes “allow expansion but protect the result”; $'…' is used to write invisible characters

Data flow: one missing pair of quotes turns one filename into two arguments

wc -l $f Parameter expansionwc -l report 2026.txt Word splitting (IFS)[wc] [-l] [report] [2026.txt] execve argv4 arguments → 2 errors wc -l "$f" Parameter expansionwc -l "report 2026.txt" Word splitting: skippedResults inside quotes are not split execve argv[wc] [-l] [report 2026.txt] Quotes (") are removed in the final quote removal step; the program never sees the quotes you wrote
Figure 3-2: the same variable; whether it is double-quoted determines how many elements end up in argv

Interactive tokenizer: how many arguments does this line get split into?

Simulated environment: HOME=/home/labadmin,USER=labadmin,f='report 2026.txt',x='*',n=3; the current directory is ~/bashlab/data/files (contains 13 odd-named files). Enter any line (or click a preset), then click “Character-by-character analysis” to watch how the quoting state machine splits words and finally yields the argv that execve receives. The simulator only implements quotes,$VAR/${VAR} expansion, word splitting and */? globbing, for understanding the rules.

UnquotedInside single quotesInside double quotesInside $'…'Word separator / escape
Ready.
The real mechanism behind the animation Bash's lexer (parse.y in read_token_word), reads character by character, tracking whether it is inside single quotes / double quotes / $' ” state; unquoted whitespace ends a word; quote characters are kept in the word, with a note that “this part was quoted”. After expansion, only unquoted parts take part in word splitting and pathname expansion, and quote removal finally deletes the quote characters. You can use printf '<%s>\n' … to verify the simulator's results.

Command reference

SyntaxPurposeNotes
printf '<%s>\n' args…See each argument's boundaries clearlyThe most-used debugging technique in this lesson
printf '%q\n' "$v"Shows output in a form safe to copy back into a shellNon-printable characters shown as $'…'
${v@Q}Parameter transformation: prints the quoted formBash 4.4+
declare -p vShows the variable's type and valueAlso works for arrays
cmd -- "$f"End-of-options markerPrevents filenames beginning with - from being treated as options.
./* or "$dir"/*Makes glob results start with ./ as a prefix.Another way to guard against - is:
set -f / set +fTurn pathname expansion off / onWhen handling data containing * data, you can use
args() { printf '%d args:' "$#"; printf ' <%s>' "$@"; echo; }   # debugging helper
f='report 2026.txt'
args $f
args "$f"
args '$f' "$f" $'tab\there'
args 'it'\''s' "it's" $'it\'s'
args "a"'b'c"$f"
args "$(echo "inner quoted")"
2 args: <report> <2026.txt>
1 args: <report 2026.txt>
3 args: <$f> <report 2026.txt> <tab	here>
3 args: <it's> <it's> <it's>
1 args: <abcreport 2026.txt>
1 args: <inner quoted>

How to verify: Whenever you are unsure, pass the arguments to args (or printf '<%s>\n') to see boundaries. Common mistakes: Using echo $x to debug: it collapses whitespace and expands wildcards, so you do not see the real value. Production use: All scripts that handle filenames, URLs, and user input.

x='  lots   of   space  '
echo $x
echo "$x"
printf '%q\n' "$f" "it's" $'a\tb'
echo "${f@Q}"
lots of space
  lots   of   space
report\ 2026.txt
it\'s
$'a\tb'
'report 2026.txt'
cd ~/bashlab/data/files
args *.txt               # each filename from the glob is one complete word, even if it contains spaces or newlines
args "*.txt"             # literal asterisk
v=$(ls); args $v | cut -c1-60    # counter-example: splitting ls output → 22 “words”
9 args: <café-ünïcode.txt> <it's.txt> <line1
line2.txt> <price $5.txt> <report 2026.txt> <say "hi".txt> <star*.txt> <tab	here.txt> <two  spaces.txt>
1 args: <*.txt>
22 args: <--verbose.log> <-n> <[draft]> <notes.md> <café-ü

Of the 9 .txt: trailing-space.txt␠ ends with a space, so it does not match,.hidden.txt is a hidden file, so it does not match. Glob results are safe; they run after word splitting, and their results are not split again. The danger is splitting ls / find 's text output again.

# filenames starting with -
cat -n           # wrong: -n is taken as an option, cat waits on stdin (Ctrl+D to exit)
cat -- -n        # right: everything after -- is an operand
cat ./-n         # right: the path starts with ./
for f in ./*; do printf '%q\n' "$f"; done | head -n 4
file #5
file #5
./--verbose.log
./-n
./\[draft\]\ notes.md
./café-ünïcode.txt

Goal: On the 15 oddly named files in ~/bashlab/data/files , write a loop that correctly counts the lines of each file for any filename, and compare it with the wrong approaches. Environment: make-data.sh has already been run. Cost: None. Risk: Read-only operations.

Wrong approach 1: parsing ls output
cd ~/bashlab/data/files
for f in $(ls); do wc -l "$f"; done 2>&1 | head -n 8
wc: unknown option -- verbose.log
Try 'wc --help' for more information.
wc: unknown option -- n
Try 'wc --help' for more information.
wc: '[draft]': No such file or directory
wc: notes.md: No such file or directory
1 café-ünïcode.txt
1 it's.txt

$(ls) output is word-split: spaces, tabs and newlines all become separators; -n is treated as an option by wc.

Wrong approach 2: used a glob but forgot the quotes
for f in *; do wc -l $f; done 2>&1 | grep -c 'No such file'
17

The glob result itself is correct, but $f when unquoted, gets split (and globbed again) one more time: report 2026.txt becomes two nonexistent files,-n and --verbose.log becomes an option, so only 3 files are counted correctly in the end.

Correct approach: glob + ./ prefix + double quotes + skip directories:
for f in ./* ./.[!.]*; do
  [[ -f $f ]] || continue
  printf '%s\t%q\n' "$(wc -l < "$f")" "${f#./}"
done
1	--verbose.log
1	-n
1	\[draft\]\ notes.md
1	café-ünïcode.txt
1	it\'s.txt
1	$'line1\nline2.txt'
1	price\ \$5.txt
1	report\ 2026.txt
1	say\ \"hi\".txt
1	star\*.txt
1	$'tab\there.txt'
1	trailing-space.txt\
1	two\ \ spaces.txt
1	.hidden.txt

./.[!.]* matches hidden files that start with a dot and whose second character is not a dot (excluding . and ..); Lesson 2 uses shopt -s dotglob nullglob to write it more concisely. wc -l < "$f" Reading the file with redirection means wc does not print the filename (Module 5). sub dir is skipped as a directory — for recursive processing, use the Lesson 5 find -print0 | xargs -0.

Nested quoting exercise: use awk to count each status code in access.log; the awk program must be protected with single quotes:
awk '{ c[$9]++ } END { for (s in c) printf "%s %d\n", s, c[s] }' ~/bashlab/data/access.log | sort
200 450
201 54
301 12
302 19
304 22
400 11
401 6
404 9
500 12
502 4
503 12

If the awk program is put in double quotes,$9 the shell first expands it into the 9th positional parameter (usually empty), so awk receives c[]++, which gives a syntax error.

Cleanup: read-only experiment, no cleanup needed. cd ~/bashlab.

Case 1: a single space causes a “mass deletion”

Problem: A well-known failure pattern: rm -rf $STEAMROOT/* when the variable is empty, it becomes rm -rf /*; another common variant is a path with spaces,rm -rf $BACKUP_DIR in BACKUP_DIR="/data/old backups" is split into /data/old and backups. Fix:① double-quote all expansions; ② for variables that must be non-empty, use "${VAR:?}"; ③ before deleting, use [[ -d $dir && $dir == /data/* ]] to validate against an allowlist; ④ ShellCheck's SC2086 (unquoted) and SC2115 ("${var:?}"/*) are set as errors in CI (Lesson 7).

Case 2: double-layer quoting when running remotely via SSH

Problem:ssh web-01 "grep '$pattern' /var/log/nginx/access.log" Fails when pattern contains a single quote, and when it contains ; it even runs extra commands. Root cause: ssh joins the arguments into one string and hands it to the remote shell which parses it again. Fix: Use printf '%q' to generate safe arguments for the remote side: ssh web-01 "grep -- $(printf '%q' "$pattern") /var/log/nginx/access.log", or pass the script via stdin: ssh web-01 bash -s -- "$pattern" < remote.sh. Limitation:%q 's output is Bash syntax, so the remote shell must also be Bash (not dash).

Case 3: JSON / YAML $

Problem:curl -d "{\"price\": \"$5\"}" emits "price": "". Fix: use single quotes for static JSON; when interpolation is needed, use jq -n --arg p "$price" '{price: $p}' to generate it (Lesson 5); do not hand-build JSON strings.

Common errors and fixes

unexpected EOF while looking for matching `''(or `"')

Cause: Quotes are unbalanced, commonly caused by writing \', or by copied “smart quotes” ’.

bash -n script.sh                     # syntax check only
grep -n "[‘’“”]" script.sh            # find Chinese/smart quotes

Fix: Use 'it'\''s' or "it's"; replace smart quotes with ASCII quotes; enable syntax highlighting in your editor.

[: too many arguments

Cause:[ $name = "web 01" ] in $name contains spaces, so after splitting [ receives too many arguments.

name='web 01'; [ $name = 'web 01' ]; echo $?

Fix:[ "$name" = 'web 01' ] or [[ $name == 'web 01' ]].

No such file or directory, but ls clearly shows this file

Cause: The filename contains spaces, trailing spaces, tabs or invisible characters, and the variable is unquoted or these characters were lost when copying.

ls -b                       # GNU ls: shows invisible characters in escaped form
printf '%q\n' *

Fix: Get the exact name using a glob or Tab completion; double-quote everywhere.

bash: !b: event not found

Cause: In interactive Bash, the ! inside double quotes triggers history expansion: echo "deploy failed!b".

Fix: Use single quotes '…!…'; or set +H turn off history expansion. Scripts (non-interactive) have no history expansion by default, so they are unaffected.

Command-line task
1. Without using double quotes, use echo to print: It's $HOME (the literal $HOME).
echo 'It'\''s $HOME'
echo $'It\'s $HOME'

Both work; inside single quotes $HOME is not expanded,$'…' in $ is literal too.

2. Take the filenames in variable f and safely pass them to a remote SSH command ls -l.
ssh linuxlab "ls -l -- $(printf '%q' "$f")"

The local shell expands first $(printf …), producing an escaped form that the remote Bash can parse correctly.

Scenario analysis question
A log-cleanup script contains find $LOG_DIR -name *.log -mtime +7 -delete. On one server it deleted only some of the logs; on another it reports “paths must precede expression”. Explain and fix it.

Two problems: ① *.log is unquoted, so the shell first does pathname expansion in the current directory to pathname expansion: when there are no .log files in the current directory, the glob stays as is and find works normally; when there is exactly one a.log it becomes -name a.log; with multiple files it becomes -name a.log b.log, and find reports “paths must precede expression”. ② $LOG_DIR is unquoted, so it is split when it contains spaces. Fix: find "$LOG_DIR" -name '*.log' -mtime +7 -delete—the wildcard must be left for find to match, so it needs quotes to stop the shell from expanding it.

Verified teaching videos

▶
Lecture 2: Shell Tools and Scripting (2020) — Missing Semester
English · single vs double quotes, variables, command substitution, globbing
▶
The Complete Bash Scripting Course - Full Length Guide to learning the Bash Shell — You Suck at Programming
English · long-form course; the author consistently stresses “quote your variables” and proper Bash habits

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided, which can be given to a video tool to generate.

Shot 1 · 0–20s
Visual: the file “report 2026.txt” is cut in half by a pair of scissors at the space.
Narration: an unquoted variable has its expanded value cut at the spaces, so one filename becomes two arguments.
Shot 2 · 20–45s
Visual: three kinds of quotes look like glass covers of different transparency: single quotes block everything, double quotes let only $ through, and $'…' turns \n into a real newline.
Narration: single quotes are all literal, double quotes allow expansion but protect the result, and dollar-single-quotes are used to write invisible characters.
Shot 3 · 45–70s
Visual: 'it'\''s' is split into three pieces and reassembled as it's.
Narration: you can't put a single quote inside single quotes, so close it, add an escaped single quote, then reopen.
Shot 4 · 70–90s
Visual: for f in ./* safely loops through filenames with newlines, spaces, or leading dashes.
Narration: loop over files with a glob, don't parse ls; double-quote every expansion.
or score ≥ 70% on the “Quiz”

Module 4 · The seven expansion steps and their order

21:00 – 28:00 · Brace → tilde → parameter / arithmetic / command substitution (left to right) → word splitting → pathname expansion → quote removal. The order determines the result: this module's core animation ties the whole “parse and execute pipeline” together
7 minutesBash 5.3 · ${ cmd; } new featureCore animation★★★★★
Learning objectives
  • Per the manual, state the Shell Operation complete processing flow of a command line: read → tokenize (including alias expansion) → parse → expand → redirect → execute → wait and collect the exit status.
  • Recite the seven expansions and their order, and use the order to explain these phenomena: {1..$n} does not take effect,x='*'; echo $x globs, and the output of command substitution is not parameter-expanded again.
  • Know which words do not undergo the full expansion: the right side of assignment statements,[[ ]] inside case words, and redirection targets (expanding to multiple words gives “ambiguous redirect”).
  • Be able to use set -x (xtrace) to observe the real command after expansion; understand Bash 5.3's ${ cmd; } and ${| cmd; }.
Prerequisites: Modules 2, 3. Importance:★★★★★ (core thread of the course)

What: the seven stages Bash goes through to process a command line (manual Shell Operation)

  1. Read input: from the terminal (readline), a script file, or -c string input. An interactive shell first performs history expansion (!!,!$).
  2. Tokenization (tokenise): following the quoting rules (Module 3), splits the input into words (word) and operators (operator): | & ; ( ) < > && || 2>&1 etc.; and on the word in command position, performs alias expansion (Module 2).
  3. Parsing: organized into simple commands, pipelines, lists (; && ||), and compound commands (if,for,{ },( )). In a simple command,NAME=value form words and redirections are set aside saved.
  4. Expansion: the remaining words go through the seven expansions in turn (see table below), producing the command name and arguments.
  5. Redirection: performs redirections and removes the redirection operators and targets from the arguments (Module 5).
  6. Execute the command: functions and builtins run in the current shell; external commands use fork + execve (Module 2).
  7. Wait and collect the exit status: a non-background command is waited for, and its status is stored in $? (Module 6).

What: the seven expansions (Shell Expansions)

#ExpansionSyntaxExample → resultKey points
1Brace brace{a,b} {1..5} {01..10..2}x{,.bak} → x x.bakgenerates plain text,is done first; it does not check whether files exist, and variables cannot be used inside (they are not yet expanded at this point).
2Tilde tilde~ ~user ~+ ~-~/bashlab → /home/labadmin/bashlabonly at the start of a word (in assignments, also after = and : ), and only when unquoted; "~" is literal
3Parameter and variable parameter$v ${v} ${v:-def} ${#v} …$USER → labadminLesson 2 covers all forms
4Command substitution command substitution$(cmd) (legacy `cmd`)$(date +%F) → 2026-11-17runs in a subshell,removes all trailing newlines; Bash 5.3 adds a non-forking ${ cmd; }
5Arithmetic arithmetic$(( expr ))$(( 3 * 4 )) → 12integer arithmetic (Lesson 2)
6Word splitting word splittingcontrolled by IFS (default: spaces, tabs, newlines)f='a b'; cmd $f → two argumentsOnly applies to the results of steps 3–5 that are unquoted results; unquoted empty results are removed
7Pathname pathname / filename* ? […] (and extglob)data/*.csv → data/servers.csvIf no match, it stays unchanged (nullglob → removed,failglob → error); set -f Turn off
+Quote removal quote removal—"a b" → a bRemoves all that were not produced by expansion quotes and backslashes; always the last step

Manual text: “The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; pathname expansion; and quote removal.” In other words, steps 2–5 belong to the same pass, processed from left to right. On supported systems there is also an eighth one: Process substitution <(cmd) / >(cmd), running alongside 2–5, expands to /dev/fd/63 such a path (Lesson 2).

Why: order determines the result — five classic cases

CaseExplained by order
n=3; echo {1..$n} Output {1..3}Brace expansion runs before parameter expansion, so at that point you see {1..$n}, which is not a valid sequence and is kept as-is. Use seq 1 "$n" or for ((i=1;i<=n;i++)).
x='{a,b}'; echo $x Output {a,b}Text produced by variable expansion is not brace-expanded again.
x='*'; echo $x List filesPathname expansion runs after parameter expansion, and it applies to unquoted results.
a='$HOME'; echo $a Output $HOMEExpansion is done in one pass, so the $ result is not expanded again (you need eval eval, and that is exactly where injection bugs come from).
v=$(printf 'a\n\n'); echo ${#v} Output 1Command substitution strips all trailing newlines; to keep them, use v=$(cmd; printf x); v=${v%x}.

How: places that skip full expansion

  • Assignment NAME=value: the right-hand side undergoes tilde, parameter, command substitution, arithmetic and quote removal,but no word splitting or pathname expansion (so files=*.log the stored value is literal *.log).
  • [[ … ]] and case: no word splitting or pathname expansion,== Right side: case the pattern is matched as a pattern match.
  • Redirection target: after expansion it must be exactly one word, otherwise bash: $out: ambiguous redirect.
  • here-document: if the delimiter is quoted (<<'EOF') the body is not expanded at all; if unquoted, parameter, command substitution and arithmetic expansion are performed (Module 5).

When: the two command substitution forms added in Bash 5.3

syntaxWhere it runsResultUse
$(cmd)Forked child shellcmd's stdout (trailing newlines removed)Portable, all versions
${ cmd; } (5.3+)Current shell, no fork; output is first written to a temp file and then read backSame as aboveReading a value from a frequently called function, and variable changes made inside the function are kept
${| cmd; } (5.3+)Current shellThe variable's value after cmd runs REPLY (cmd's output is still displayed as usual)“return value” style function: f() { REPLY=…; }

Both forms require whitespace after the opening brace (or | a tab), and a semicolon ; or newline, consistent with { list; } the standard form. Bash 5.2 and earlier report “bad substitution”, so do not use these in scripts that must run on older versions.

Common misconceptions① “Quotes are removed in the first step”: quotes are kept until the end, and every earlier step has to check them. ② “Word splitting applies to the whole line”: it only applies to unquoted expansion results; literals you type directly a b contain spaces that are handled during tokenization. ③ “* no match means empty” — by default the pattern is kept as-is (so rm *.tmp with no .tmp files it reports “cannot remove '*.tmp'”). ④ “$(…) output is kept as-is” — all trailing newlines are removed, and unquoted output is also split and globbed. ⑤ “~ expands everywhere”—"~/x",a~,--dir=~/x are not expanded in non-assignment contexts.

Pipeline: parsing and executing one command line

Parsing stage (input text) ① Read inputreadline · history expansion ② Tokenizewords · operators · quotes ③ Aliasescommand position · unquoted ④ Parse syntaxassignments · redirections separated Expansion stage (seven steps) ⑤ Braces{a,b} {1..3} ⑥ tilde · parameter · arithmetic · command substitutionsame pass, left to right (process substitution also happens here) ⑦ Word splittingIFS · unquoted only ⑧ Pathname* ? [ ] · unquoted only ⑨ Quote removalRemoves ' " \ Execution stage ⑩ Redirectionsopen · dup2 ⑪ Find commandfunctions · builtins · hash · PATH ⑫ Executebuiltins: this process · external: fork → execve ⑬ Exit statuswait → $? · 0 / 1–125 / 126 / 127 / 128+N Implementation detail: for external commands, ⑩ happens in the child process after fork and before execve; for builtins, ⑩ runs in the current shell and is restored afterwards.
Figure 4-1: core flow of this lesson: parse → seven-step expansion → redirection → lookup → execution → exit status

Data flow: how one word changes across the seven steps

Input: cp ~/bashlab/data/{servers,inventory}.* "$dest/$(date +%F)"/ (dest='/tmp/my backup') ⑤ Braces: cp ~/bashlab/data/servers.* ~/bashlab/data/inventory.* "$dest/$(date +%F)"/ ⑥ Tilde/parameter/command substitution: cp /home/labadmin/bashlab/data/servers.* /home/labadmin/bashlab/data/inventory.* "/tmp/my backup/2026-11-17"/ ⑦ Word splitting: “my backup” inside quotes is not split → still 4 words ⑧ Pathname: servers.* → servers.csv; inventory.* → inventory.json (the quoted part does not take part in globbing) ⑨ Quote removal → argv = [cp] [/home/labadmin/bashlab/data/servers.csv] [/home/labadmin/bashlab/data/inventory.json] [/tmp/my backup/2026-11-17/] Without the double quotes, step ⑦ splits “/tmp/my” and “backup/2026-11-17/” apart, so cp either copies the three files into the directory backup/2026-11-17/ or reports an error
Figure 4-2: each step only does its own job; quote protection lasts until the last step

Core animation: parsing and executing one command line

Pick a command line and step through its 13 stages to watch how the words change (yellow = quote-protected parts, blue = words changed in this step, red = operators / redirections). The file descriptor table is on the right, and the log at the bottom shows set -x or strace -f the actual output you would see (simplified). Environment: alias ll='ls -l',out="$HOME/bashlab/tmp/ls out.txt",f='report 2026.txt',USER=labadmin.

Current words
File descriptor table
0 → /dev/pts/0
1 → /dev/pts/0
2 → /dev/pts/0
Ready.
The real mechanism behind the animation The stage breakdown comes from the Bash manual Shell Operation,Simple Command Expansion,Command Search and Execution (three sections); in implementation, lexing / parsing happens in parse.y, and expansion happens in subst.c (expand_words: braces → expand_word_internal handles tilde, parameter, command substitution, arithmetic → word_split → glob_expand_word_list → quote removal), and execution happens in execute_cmd.c (execute_simple_command: builtins go through execute_builtin_or_function, external commands go via execute_disk_command → make_child fork → child process do_redirections → shell_execve). If the command is not found, Bash still forks and in the child calls command_not_found_handle or prints an error and exits with 127.

Command table

Command / optionPurposeNotes
set -x / set +xPrints each command after expansion, before it runsPrefix is $PS4 (default + , with one more + per nesting level)
PS4='+ ${BASH_SOURCE##*/}:${LINENO}: 'Makes xtrace show file name and line numberLesson 4 debugging tip
printf '<%s>\n' …Check argument boundaries after expansionModule 3's args function
shopt -s nullglob / failglobOn no match: removed / errorAll off by default
shopt -s dotglob / globstar / extglobMatch hidden files / ** recursive / !(…) and other extended patternsCovered in Lesson 2
set -fTurn off pathname expansionUse temporarily when handling text that contains wildcards
IFS=…Change the word-splitting delimitersChange applies only to the current command: IFS=, read -r …
args() { printf '%d args:' "$#"; printf ' <%s>' "$@"; echo; }
args {a,b}{1,2} pre-{x..z} {01..03} {z..a..5}
args x{,.bak}
n=3; args {1..$n}
x='{a,b}'; args $x
args ~ ~/bashlab "~" a~
p=~/bin:~/sbin; echo "$p"
a='$HOME'; args $a "$a"
e=''; args $e "$e" ''
16 args: <a1> <a2> <b1> <b2> <pre-x> <pre-y> <pre-z> <01> <02> <03> <z> <u> <p> <k> <f> <a>
2 args: <x> <x.bak>
1 args: <{1..3}>
1 args: <{a,b}>
4 args: </home/labadmin> </home/labadmin/bashlab> <~> <a~>
/home/labadmin/bin:/home/labadmin/sbin
2 args: <$HOME> <$HOME>
2 args: <> <>

How to verify: Last line: an unquoted empty expansion $e is removed (it does not become an empty argument), while "$e" and '' each is one empty argument, which is why [ $e = x ] the command fails. Common mistake: Thinking {1..$n} will work. Production use:cp app.conf{,.bak} one-click backup; mkdir -p ~/bashlab/{data,tmp,bin,scripts}.

set -x
echo {dev,prod}-$USER "$(date +%F)" ~/x
f='report 2026.txt'; : $f "$f"
set +x
++ date +%F
+ echo dev-labadmin prod-labadmin 2026-11-17 /home/labadmin/x
dev-labadmin prod-labadmin 2026-11-17 /home/labadmin/x
+ f='report 2026.txt'
+ : report 2026.txt 'report 2026.txt'
+ set +x

++ Indicates the command substitution ran in one subshell level. xtrace uses quotes to mark “this is a single argument containing a space”: report 2026.txt are two arguments, and 'report 2026.txt' is one.

cd ~/bashlab
args nomatch*.zz                                   # default: kept as-is
shopt -s nullglob;  args nomatch*.zz; shopt -u nullglob
out='a b'; echo hi > $out; echo "rc=$?"           # redirect target gets split
IFS=, read -r name env region _ <<< 'web-01,dev,canadacentral,10.10.1.21,web'; args "$name" "$env" "$region"
1 args: <nomatch*.zz>
0 args: <>
bash: $out: ambiguous redirect
rc=1
3 args: <web-01> <dev> <canadacentral>
# Bash 5.3+: command substitution without fork
counter=0
next() { counter=$((counter + 1)); echo "$counter"; }
a=$(next); b=$(next); echo "a=$a b=$b counter=$counter"     # subshell: counter unchanged
c=${ next; }; d=${ next; }; echo "c=$c d=$d counter=$counter"  # current shell: counter is modified
getval() { REPLY="value-$1"; }
v=${| getval 42; }; echo "$v"
a=1 b=1 counter=0
c=1 d=2 counter=2
value-42

Goal: Predict the expansion results of the 6-line command first, then verify them; then use expansion to write a one-line command that creates directories and backups in bulk. Environment:~/bashlab, data already generated. Cost: None.

Prediction exercise: on paper, write down the number and content of arguments for each line, then run:
cd ~/bashlab/data
args() { printf '%d args:' "$#"; printf ' <%s>' "$@"; echo; }
v='*.csv  *.json'
args $v
args "$v"
args {servers,inventory}.*
args ~/"bashlab"/data
args $(echo '*.yaml')
args "$(echo '*.yaml')"
2 args: <servers.csv> <inventory.json>
1 args: <*.csv  *.json>
2 args: <servers.csv> <inventory.json>
1 args: </home/labadmin/bashlab/data>
1 args: <config.yaml>
1 args: <*.yaml>

Line 5: the unquoted command substitution result → word splitting → pathname expansion,*.yaml matches config.yaml. Line 4: ~ is at the start of the word and unquoted, so the quotes after it do not affect it.

Use set -x to watch the access.log counting command:
code=50; log=~/bashlab/data/access.log
set -x
grep -c "\" ${code}[0-9] " "$log"
set +x
+ grep -c '" 50[0-9] ' /home/labadmin/bashlab/data/access.log
28
+ set +x

28 = 500×12 + 502×4 + 503×12. If the pattern is written as ' 50[0-9] ' (without the leading quote), it also matches one record whose response size is exactly 506 bytes (line 52, status 201), giving 29. The dataset deliberately keeps this trap (Lesson 5 solves it thoroughly with awk field comparison).

Batch operations with brace expansion:
mkdir -p ~/bashlab/tmp/exp/{dev,staging,prod}/{logs,conf}
cp ~/bashlab/data/config.yaml ~/bashlab/tmp/exp/prod/conf/config.yaml{,.bak}  # Wrong: cp needs a source and a destination
cp ~/bashlab/data/config.yaml ~/bashlab/tmp/exp/prod/conf/
cp ~/bashlab/tmp/exp/prod/conf/config.yaml{,.bak}                               # Correct: expands to source and destination
find ~/bashlab/tmp/exp -type f | sort
cp: target '/home/labadmin/bashlab/tmp/exp/prod/conf/config.yaml.bak' is not a directory
/home/labadmin/bashlab/tmp/exp/prod/conf/config.yaml
/home/labadmin/bashlab/tmp/exp/prod/conf/config.yaml.bak

The first cp expands to three arguments (source,…/config.yaml,…/config.yaml.bak), cp requires the last one to be a directory. The error text varies with the GNU coreutils version (for example, 9.x may show cp: target '…/config.yaml.bak': No such file or directory) with the same meaning. Brace expansion is pure text substitution, so previewing with echo is good practice.

(Optional, Bash 5.3) Compare $(…) and ${ …; } speed:
time for i in {1..2000}; do x=$(printf '%s' "$i"); done
time for i in {1..2000}; do x=${ printf '%s' "$i"; }; done

The latter does not fork and is usually about an order of magnitude faster (exact numbers vary by machine; on 5.2 the second line is a syntax error).

Cleanup: rm -rf -- ~/bashlab/tmp/exp

Case 1: the date-named directory in a backup script “disappeared”

Problem:dest=/backup/$(hostname)-$(date +%F %H%M) Reports date: extra operand '%H%M', or with the other form dest=/backup/$(date '+%F %H%M') , it mkdir $dest creates two directories. Root cause: The first is that arguments inside the command substitution get split (%F and %H%M became two arguments to date); the latter is that the mkdir argument is unquoted. Fix: Avoid spaces in the timestamp (date +%Y%m%dT%H%M%S), and quote all expansions: mkdir -p -- "$dest".

Case 2: in CI rm -rf build/* fails when the directory is empty

Problem: In CI images with failglob enabled,build/ when the glob matches nothing, the whole command reports “no match” and aborts the pipeline. Fix: Do not rely on globbing: use find build -mindepth 1 -delete, or explicitly set shopt -s nullglob where globbing is needed, and check the array length (Lesson 2). Caveat: Default shopt settings can differ between CI images, so scripts should explicitly set the options they depend on at the top.

Case 3: eval-built command causes injection

Problem: An ops tool concatenates the user-supplied hostname into eval "ssh $host uptime", and someone entered web-01; rm -rf ~. Root cause:eval Letting the expanded result go through the full parsing and expansion process a second time. Fix: Do not use eval to build commands; store arguments in an array cmd=(ssh -- "$host" uptime); "${cmd[@]}", and validate input against an allowlist (for example, allow only ^[a-z0-9-]+$).

Common errors and fixes

bash: $out: ambiguous redirect

Cause: The redirection target expanded to zero or more than one word: the variable is undefined or empty, or it contains spaces and is unquoted.

declare -p out

Fix:> "$out"; and check that the variable is assigned: > "${out:?out is not set}".

ls: cannot access '*.log': No such file or directory

Cause: The current directory has no matching files, so the wildcard was passed to ls as-is.

pwd; compgen -G '*.log' || echo "no match"

Fix: Confirm the directory; in the script, use nullglob plus an array to check the count.

bash: ${ next; }: bad substitution

Cause: The current Bash is older than 5.3 (for example, 5.2 on Ubuntu 24.04, or 3.2 on macOS), so it does not support the new command substitution syntax; or there is no whitespace after the opening brace.

echo "$BASH_VERSION"

Fix: Upgrade to 5.3, or switch back to $(…); when compatibility is needed, check at the start of the script (( BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 503 )).

for i in {1..$n} loops only once, and the value of i is {1..10}

Cause: Brace expansion happens before parameter expansion.

n=10; for ((i = 1; i <= n; i++)); do echo "$i"; done | tail -n1

Fix: Use an arithmetic for loop or seq (Lesson 2).

Command-line exercise
1. Using one command, create ~/bashlab/tmp/r/2026-11-{01..07} seven directories, and confirm the count with one command.
mkdir -p ~/bashlab/tmp/r/2026-11-{01..07} && ls -d ~/bashlab/tmp/r/*/ | wc -l

Brace expansion supports zero-padded sequences ({01..07}). Result: 7.

2. Write a one-line command that prints “the total number of lines in all .csv and .json files in bashlab/data under the current user's home directory”, and that works correctly when HOME contains spaces.
cat -- "$HOME"/bashlab/data/*.{csv,json} | wc -l

"$HOME" Quote to prevent splitting,/bashlab/data/*.{csv,json} is outside the quotes; brace expansion first produces two patterns, then each is globbed. Result: 13 + 14 = 27 (actual output).

Scenario analysis exercise
A colleague wrote exclude='--exclude=*.tmp --exclude=.cache', and then rsync -a $exclude src/ dst/. It mostly works, but when run in a certain directory, rsync errors out or the exclude rules stop working. Explain it using the expansion order, and give a robust version.

$exclude Unquoted → word splitting into two words (what the author wanted) → but then pathname expansion is also done pathname expansion: --exclude=*.tmp is itself a glob pattern; if the current directory happens to contain a file named --exclude=a.tmp (or failglob / nullglob is enabled), the result changes. A more common problem is that you cannot express an exclude path containing spaces at all. The robust approach is an array: exclude=(--exclude='*.tmp' --exclude='.cache'); rsync -a "${exclude[@]}" src/ dst/: each element is exactly one argument, with no splitting or globbing.

Verified instructional videos

▶
Lecture 2: Shell Tools and Scripting (2020) — Missing Semester
English · variables, command substitution, process substitution, globbing and brace expansion
▶
Bash Scripting Full Course 3 Hours — linuxhint
English · long course; view the variable and expansion sections by chapter

No verified video was found that walks through the “seven-step expansion” in the order of the Bash manual; refer to this module's core animation and storyboard script instead.

Official docs

Video storyboard script (about 2 minutes)

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: a command line enters a factory assembly line; the first station cuts it into colored blocks (words) and red blocks (operators).
Narration: after you press Enter, Bash first reads the input, tokenizes it, replaces aliases and parses the syntax.
Shot 2 · 20–60s
Visual: seven stations light up in turn: braces duplicate blocks, tilde turns into the home directory, dollar signs are replaced by values, the word-splitting scissors cut only blocks without a yellow protective cover, asterisks turn into file names, and finally the protective covers are removed.
Narration: the seven expansion steps always run in a fixed order: braces, tilde, parameter, arithmetic and command substitution, word splitting, pathname, quote removal.
Shot 3 · 60–95s
Visual: {1..$n} At the first station, n has not yet become 3, so it passes through unchanged.
Narration: order determines the result: when brace expansion runs, the variable has no value yet.
Shot 4 · 95–120s
Visual: at the end of the pipeline, redirection connects the plumbing, the command is looked up, fork creates a child process, execve runs, and exit code 0 returns to $?.
Narration: only after expansion comes redirection, command lookup and execution; finally, the exit status tells you the result.
or score ≥ 70% on the quiz

Module 5 · Redirection and file descriptors

28:00 – 35:00 · Every process has a “file descriptor table”; redirection means, before the command runs,from left to right rewrites this table
7 minutesBash 5.3 · POSIX★★★★★
Learning objectives
  • Understand file descriptors (fd): 0 stdin, 1 stdout, 2 stderr; the fd table is copied on fork and preserved on execve.
  • Master all common redirections: < > >> 2> 2>&1 &> &>> |& >| <> << <<- <<< n>&-.
  • Use the “copy fd” mental model to explain > f 2>&1 and 2>&1 > f differ, and be able to send only stderr into a pipe.
  • Use exec to redirect output for an entire script, open custom fds (exec 3>,exec {fd}>), and understand the quoting rules for here-documents.
Prerequisites: Module 4 (redirection targets are also expanded). Importance:★★★★★

What: file descriptors and redirection

A file descriptor is an index into a table the kernel maintains for each process; each entry points to an “open file” (regular file, terminal, pipe, socket,/dev/null). By convention: 0 = standard input, 1 = standard output, 2 = standard error. A program simply writes normal output to fd 1 and errors to fd 2, without knowing where they end up, which is exactly why redirection works.

SyntaxMeaning (what it does to the fd table)Typical use
< fileOpens file read-only, on fd 0wc -l < access.log (wc does not print a file name)
> fileTruncates or creates file, on fd 1cmd > out.txt
>> fileOpens in append mode (O_APPEND), on fd 1logging
2> fileSame as >, but on fd 2find / … 2>/dev/null
2>&1Copies what fd 1 currently points to onto fd 2 (dup2(1, 2))merge output
&> file / &>> fileBash shorthand: same as > file 2>&1 / >> file 2>&1Interactive shortcut (not supported by POSIX sh)
cmd1 |& cmd2Bash shorthand: same as cmd1 2>&1 | cmd2Same as above
>| fileStill overwrites even when noclobber is enabled.Together with set -o noclobber
<> fileopens fd 0 for read-writeRare: device files
n>&- / n<&-Closes fd nexec 3>&-
<<EOF … EOFhere-document: the body becomes fd 0multi-line input, generating config files
<<-EOFSame as above, and strips leading Tab (tabs, not spaces)Used in indented code blocks
<<< "str"here-string: str plus a newline as fd 0read -r a b <<< "$line"

Why: why stdout and stderr need to be separated

Pipes only connect fd 1: cmd | grep x In Write data to stdout; write logs / diagnostics / errors to stderr (opsctl's log::info and similar functions write to stderr), so that opsctl servers list | jq … can work reliably.

How: left to right, duplicating rather than “linking”

2>&1 does not mean “make 2 always follow 1”, but rather “at this moment, wherever points, make 2 point there too”. So order matters:

SyntaxAfter step 1After step 2Result
cmd > f 2>&11 → f, 2 → terminal2 → f (copies 1)both go to f ✓
cmd 2>&1 > f2 → terminal (copies 1, which is still the terminal at this point)1 → fonly stdout goes to f; errors still appear on screen
cmd 2>&1 >/dev/null | grep x2 → pipe (copies 1)1 → /dev/nullonly stderr goes into the pipe
cmd > f 2> f1 → f (first open)2 → f (second open, separate offset)they overwrite each other and the content gets garbled ✗

Pipes | are set up before all redirections , so they are established first: cmd 2>&1 | grep In 2>&1 , the command runs with fd 1 already set to the pipe's write end.

When: exec and custom fds

  • exec >>"$log" 2>&1: exec With no command, the redirection applies to the current shell itself, so all later output from the script goes to the log.
  • exec 3> file … echo x >&3 … exec 3>&-: open once and write many times; more efficient than repeating >> file open and close in a loop (every iteration).
  • exec {fd}> file (Bash 4.1+): have Bash automatically allocate a free fd ≥ 10 and store it in the variable fd, to avoid clashing with other code; Lesson 4's flock lock uses it.
  • Bash also emulates some special paths: /dev/stdin,/dev/stdout,/dev/stderr,/dev/fd/N, and (when enabled at compile time) /dev/tcp/host/port,/dev/udp/host/port.
Common misconceptions① “2>&1 > f and > f 2>&1 are the same”—the order changes the result. ② “sudo cmd > /etc/x will write the file as root”—the redirection is opened by your shell, and sudo only elevates cmd; use cmd | sudo tee /etc/x >/dev/null. ③ “cat file | grep and grep < file are the same”—the result is the same, but the former spawns an extra process; more importantly, wc -l file and wc -l < file produce different output formats. ④ “here-string has no trailing newline”—<<< always appends a newline. ⑤ “commands still run when a redirection fails”—when a redirection fails, the command does not run at all, and its exit status $? is 1.

fd table: wc -l access.log nosuch.log > out.txt 2>&1

Initial (inherited from bash) 0 1 2 /dev/pts/0 After running “> out.txt” 0 1 2 /dev/pts/0 out.txt After running “2>&1” (dup2(1,2)) 0 1 2 /dev/pts/0 out.txt System call (visible with strace -f, in the forked child process, before execve) openat(AT_FDCWD, "out.txt", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3 → dup2(3, 1) → close(3) → dup2(1, 2) execve("/usr/bin/wc", ["wc", "-l", "access.log", "nosuch.log"], …): the fd table is passed to wc unchanged
Figure 5-1: redirections rewrite the fd table from left to right; 2>&1 is “copy the current target”, not “permanently follow”

Data flow: combining pipes and redirections

wc -l access.log nosuch.log 2>&1 >/dev/null | sed 's/^/ERR: /' wcfd1 → /dev/nullfd2 → pipe write end /dev/null (discards the 611-line count) pipe sedfd0 ← pipe read end Terminal: ERR: … Order: first create the pipe (fd1 = pipe) → 2>&1 (fd2 = pipe) → >/dev/null (fd1 = /dev/null)
Figure 5-2: the classic way to send only stderr into a pipe

File descriptor table animation: the ordering trap

Pick a form and step through to see where fd 0/1/2 (and 3) point as Bash applies each redirection left to right in the child process; then check where the command's wc -l access.log nosuch.log two lines of normal output and the one error line end up.

fd table
Final destination
(not started yet)
Ready.
The real mechanism behind the animation Bash's do_redirections (redir.c) processes redirections in the order they appear: for file redirections, use open open to get a new fd, then dup2 dup2 to the target number; n>&m directly dup2(m, n); n>&- calls close(n). For builtins, Bash first copies the overwritten fd to a position ≥ 10 to save it, and restores it when the command finishes. When the same file is opened twice, each fd has its own file offset, so the later write overwrites the earlier one; the garbled output in the animation is what was actually observed on Bash 5.2 + GNU wc.

Command table

ScenarioSyntaxNotes
Write both output and errors to a filecmd > f 2>&1 or cmd &> fIn scripts, the former is recommended (POSIX)
Discard errorscmd 2>/dev/nullDon't discard by habit; first confirm the errors don't matter
Send only errors into a pipecmd 2>&1 >/dev/null | …See animation
Output to screen and file at oncecmd 2>&1 | tee -a logtee reads stdin, writes to stdout and the file
Send the whole script's output to a logexec >>"$log" 2>&1Put at the top of the script
Open / close a custom fdexec {fd}>"$f" … exec {fd}>&-Bash 4.1+
Prevent accidental overwriteset -o noclobber; force with >|; suited for interactive shells
Empty the file: > fKeeps inode and permissions (useful for log rotation)
cd ~/bashlab/data; T=~/bashlab/tmp
wc -l access.log nosuch.log > $T/a.txt 2>&1; echo "== >f 2>&1"; cat $T/a.txt
echo "== 2>&1 >f"; wc -l access.log nosuch.log 2>&1 > $T/b.txt; echo "-- file:"; cat $T/b.txt
echo "== > f 2> f"; wc -l access.log nosuch.log > $T/d.txt 2> $T/d.txt; cat $T/d.txt
== >f 2>&1
  611 access.log
wc: nosuch.log: No such file or directory
  611 total
== 2>&1 >f
wc: nosuch.log: No such file or directory
-- file:
  611 access.log
  611 total
== > f 2> f
wc: nosuch.log: N  611 total
or directory

How to verify: The garbled output in the last example is the evidence for “two independently opened fds each writing from offset 0 and overwriting each other”. Common mistake: Thinking 2>&1 >f will also write errors to the file. Production use: cron / systemd jobs write output to log files for troubleshooting.

# Handle only stderr; here-doc and here-string
wc -l access.log nosuch.log 2>&1 >/dev/null | sed 's/^/ERR: /'
cat <<-EOF
	tab-stripped $((1+1))
	EOF
cat <<'EOF'
no $expansion `here`
EOF
tr a-z A-Z <<< "here string"
od -c <<< "x" | head -n1
ERR: wc: nosuch.log: No such file or directory
tab-stripped 2
no $expansion `here`
HERE STRING
0000000   x  \n

<<- Only strips leading Tab; if the editor converts Tabs to spaces, the end marker EOF can no longer be found (see troubleshooting). <<'EOF' with a quoted delimiter, the body's $ and backticks are not expanded — most often used when generating scripts or config templates.

# Read servers.csv line by line on an fd; use {fd} to allocate an fd automatically
exec 3< servers.csv
read -r -u 3 header; read -r -u 3 first
exec 3<&-
echo "header=$header"; echo "first=$first"
exec {w}> ~/bashlab/tmp/fd.txt; echo "fd=$w"
echo line1 >&"$w"; echo line2 >&"$w"
exec {w}>&-; cat ~/bashlab/tmp/fd.txt
header=name,env,region,ip,role
first=web-01,dev,canadacentral,10.10.1.21,web
fd=10
line1
line2

Goal: Write a small script ~/bashlab/scripts/split-log.sh: write the 4xx and 5xx requests in access.log to two separate files, write statistics to stdout, write diagnostics to stderr, and append the whole run to run.log. Environment:~/bashlab. Cost: None. Risk: Only writes to ~/bashlab/tmp.

Write the script (note that the here-doc delimiter is quoted, so the script content is written as-is):
cat > ~/bashlab/scripts/split-log.sh <<'EOF'
#!/usr/bin/env bash
log=${1:-$HOME/bashlab/data/access.log}
out=$HOME/bashlab/tmp
echo "reading $log" >&2                       # diagnostics → stderr
grep '" 4[0-9][0-9] ' "$log" > "$out/4xx.log"
grep '" 5[0-9][0-9] ' "$log" > "$out/5xx.log"
printf '4xx=%d 5xx=%d\n' "$(wc -l < "$out/4xx.log")" "$(wc -l < "$out/5xx.log")"   # data → stdout
EOF
chmod +x ~/bashlab/scripts/split-log.sh
Observe stdout and stderr separately:
cd ~/bashlab
scripts/split-log.sh                       # both appear on screen
scripts/split-log.sh 2>/dev/null           # only data remains
scripts/split-log.sh >/dev/null            # only diagnostics remain
reading /home/labadmin/bashlab/data/access.log
4xx=26 5xx=28
4xx=26 5xx=28
reading /home/labadmin/bashlab/data/access.log

4xx = 400×11 + 401×6 + 404×9 = 26; 5xx = 28.

Append the whole run to run.log, while the screen still shows:
scripts/split-log.sh 2>&1 | tee -a tmp/run.log
scripts/split-log.sh data/nosuch.log >> tmp/run.log 2>&1; echo "rc=$?"
cat tmp/run.log
reading /home/labadmin/bashlab/data/access.log
4xx=26 5xx=28
rc=0
reading /home/labadmin/bashlab/data/access.log
4xx=26 5xx=28
reading data/nosuch.log
grep: data/nosuch.log: No such file or directory
grep: data/nosuch.log: No such file or directory
4xx=0 5xx=0

Note rc=0: the script's last command, printf, succeeded, so the earlier grep failure was “swallowed”. This is the problem Lesson 4 set -e will solve; Module 6 first teaches you to check exit status.

noclobber to prevent accidental overwrites:
set -o noclobber
echo test > tmp/4xx.log; echo "rc=$?"
echo test >| tmp/4xx.log; set +o noclobber
bash: tmp/4xx.log: cannot overwrite existing file
rc=1
Cleanup: rm -f -- ~/bashlab/tmp/{4xx,5xx,run,fd,a,b,d}.log ~/bashlab/tmp/{a,b,d,fd}.txt (keep split-log.sh).

Case 1: a cron job “did nothing” and left no logs at all

Problem: The backup job runs every night, but one day it turns out there have been no successful backups for two weeks, and there is no record of any failure. Root cause: The crontab entry is 0 2 * * * /opt/backup.sh > /dev/null, and cron tries to email stderr, but the server has no MTA configured. Fix: At the start of the script, exec >>/var/log/backup.log 2>&1 and print a timestamp at each step; or hand it to a systemd timer, whose output goes automatically to journald; add failure alerts for critical jobs (Lesson 6).

Case 2: sudo echo … > /etc/… fails

Problem:sudo echo "net.ipv4.ip_forward=1" > /etc/sysctl.d/99-lab.conf Reports Permission denied. Root cause: The redirection is performed by the current user's shell (step ⑩ of the Module 4 pipeline), and sudo only applies to echo. Fix:echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-lab.conf >/dev/null, or sudo sh -c '…'.

Case 3: after log rotation, the process keeps writing to a “deleted” file

Problem: The ops team ran rm app.log , but disk space was not freed, and the new app.log stayed empty. Root cause: The process's fd still points to the deleted inode. Fix: To empty a file, use : > app.log (truncates the same inode), or have logrotate use copytruncate / tell the process to reopen the log; for troubleshooting, use ls -l /proc/<pid>/fd | grep deleted (Linux course, Lesson 7).

Common errors and fixes

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

Cause: The end marker has spaces around it, or uses <<- but is indented with spaces instead of tabs, or CRLF line endings turn the end line into EOF\r.

grep -n 'EOF' script.sh | cat -A | head

Fix: Put the end marker alone on its own line at column 0; when using <<- , indent with tabs only; convert to LF line endings.

bash: /etc/x: Permission denied (same even with sudo)

Cause: The redirection is performed by the regular user's shell before sudo runs.

Fix:… | sudo tee /etc/x >/dev/null; to append, use tee -a.

bash: file: cannot overwrite existing file

Cause: Option noclobber is enabled (possibly set in /etc/bash.bashrc or in a personal config).

set -o | grep noclobber

Fix: When you are sure you want to overwrite, use >|; scripts should not rely on interactive shell configuration.

bash: 3: Bad file descriptor

Cause: Writing to an fd that is not open (or has been closed): echo x >&3 without first running exec 3>…, or opening it in a subshell and using it in the parent shell.

ls -l /proc/$$/fd

Fix: In the same shell, first run exec 3>file; preferably use exec {fd}>file and check the variable.

Command-line exercise
1. Count the lines in access.log containing POST requests, with output that is only the number (no file name).
grep -c 'POST' < ~/bashlab/data/access.log

Actual result: 87. With input redirection, grep does not know the file name,wc -l < file the same principle applies.

2. Swap a command's stdout and stderr (errors go into the pipe, normal output is shown on screen).
cmd 3>&1 1>&2 2>&3 3>&- | grep …

fd 3 temporarily holds the “pipe”, 1 becomes the terminal (the original 2), 2 becomes the pipe (the saved 3), and finally close 3.

Scenario analysis exercise
A deployment script contains ./migrate.sh 2>&1 > migrate.log | tee -a deploy.log, and a colleague complains that migrate.log has no error messages while deploy.log only has error messages. Explain why, and give a version that matches the intent (both files log all output).

The pipe is set up first: fd 1 = pipe. 2>&1 copy fd 2 to the pipe; then > migrate.log change fd 1 to the file. Result: stdout → migrate.log, stderr → pipe → tee → deploy.log and the screen. Correct form: ./migrate.sh 2>&1 | tee migrate.log | tee -a deploy.log, or ./migrate.sh > migrate.log 2>&1; cat migrate.log >> deploy.log. Note: tee after the pipeline, $? is tee's status; use PIPESTATUS or pipefail to get migrate.sh's status (Module 6).

Verified instructional videos

▶
The Complete Bash Scripting Course - Full Length Guide to learning the Bash Shell — You Suck at Programming
English · long course, including chapters on redirection and file descriptors
▶
Lecture 1: Course Overview + The Shell (2020) — Missing Semester
English · the second half covers I/O streams, redirection and pipes

A search for “bash redirection file descriptors 2>&1” found no verified video that specifically explains the fd duplication order; refer to this module's animation.

Official docs

Video storyboard script (about 90 seconds)

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

Shot 1 · 0–20s
Visual: a process has three pipes, with 0 as the intake, 1 as the outflow and 2 as the drain, all connected to the terminal.
Narration: every process has a file descriptor table: zero is input, one is output, two is error.
Shot 2 · 20–50s
Visual: > out.txt Reconnect pipe 1 to a file; 2>&1 connect pipe 2 to wherever pipe 1 is connected at that moment.
Narration: redirections run from left to right. “Two greater-than and one” means: copy whatever 1 points to right now.
Shot 3 · 50–75s
Visual: with the order reversed, pipe 2 still connects to the terminal, and errors still spray onto the screen.
Narration: get the order wrong, and errors never reach the file.
Shot 4 · 75–90s
Visual: exec >> log 2>&1 Connect the whole shell's pipes to the log.
Narration: with no command, exec applies the redirection to the current shell itself.
or score ≥ 70% on the quiz

Module 6 · pipes, exit status and && / ||

35:00 – 42:00 · Every command reports success or failure with a number from 0–255; commands in a pipeline run at the same time, and by default only the last command's status counts
7 minutesBash 5.3 · PIPESTATUS · pipefail★★★★★
Learning objectives
  • Understand exit status: 0 = success, non-zero = failure; the meanings of 126 / 127 / 128+N; exit values are taken modulo 256; $? is overwritten after every command.
  • Understand Pipelines: each stage runs in its own child process, and all stages run concurrently, connected through a kernel pipe buffer; by default the pipeline's status is the last stage's status.
  • Use PIPESTATUS and set -o pipefail to get each stage's status, and understand SIGPIPE (141) and the “false failure” it causes.
  • Use list operators correctly: ; && || & and !, avoiding the trap that a && b || c is not equivalent to if-else.
Prerequisites: Module 5. Importance:★★★★★ (the foundation of strict mode in Lesson 4)

What: exit status

ValueMeaningExample
0Success (in if / && it is “true”)true, a match found by grep
1General failure; many tools use it to mean “result is no”grep No match,diff differences found,false, redirection failure
2often used for “usage error / serious error”grep file does not exist,ls access failed, Bash builtin usage error; opsctl uses it for usage errors.
126Command found but cannot be executedlacks x permission, or is a directory
127Command not foundtypo, PATH problem
128+NTerminated by signal NCtrl+C (SIGINT=2) → 130; kill (SIGTERM=15) → 143; SIGKILL → 137; SIGPIPE (13) → 141
> 255Taken modulo 256:exit 300 → 44; do not use

A function's status is the value of return n (or the last command's status); a subshell ( … ) 's status is that of its last command or exit value. opsctl convention: 0 success, 1 general error, 2 usage error, 3 missing dependency.

Why: why a pipeline can “swallow” errors

Pipelines like cmd1 | cmd2 | cmd3 , Bash forks a child process for each stage and uses pipe() to create a kernel buffer (64 KiB by default on Linux) connecting the previous stage's fd 1 to the next stage's fd 0,all stages start at the same time. Bash waits for all stages to finish, but by default uses the last stage's status as the pipeline's status. So cat nosuch.log | wc -l output 0 and $? is 0 — an error turns into a “0 lines” correct result.

How: three tools

  • PIPESTATUS: an array holding the status of each stage of the most recent foreground pipeline: ${PIPESTATUS[0]},${PIPESTATUS[@]}. It is overwritten by the next command, so save it immediately: cmd1 | cmd2; ps=("${PIPESTATUS[@]}").
  • set -o pipefail: the pipeline's status becomes “the rightmost non-zero status” (0 only if all are 0). In Lesson 4's strict mode, set -euo pipefail is one part of it.
  • !: placed in front of a pipeline, it negates the status: if ! grep -q PATCH access.log; then ….

SIGPIPE trap:yes | head -n1 in which head exits after reading one line, so yes gets SIGPIPE when it writes again and is terminated (status 141). With pipefail on, the whole pipeline “fails” even though the result is fully correct. For … | head this kind of pipeline: either leave pipefail off, or check PIPESTATUS and treat 141 as normal.

When: list operators

OperatorMeaningExample
a ; b (or newline)run in sequence, regardless of a's resultcd /tmp; ls (if cd fails, ls runs in the wrong directory!)
a && brun b only if a succeeds (0)cd "$dir" && rm -f -- *.tmp
a || brun b only if a fails (non-zero)command -v jq >/dev/null || { echo "need jq" >&2; exit 3; }
a &runs in a background subshell; $! is its PID,wait waits forlong_job & pid=$!; …; wait "$pid"
{ a; b; } / ( a; b )groups (current shell / subshell){ date; uptime; } > status.txt

&& and || have the same precedence and associate left to right, so in a && b || c ,when b fails, c also runs—it is not an if-then-else. To express “do b on success, otherwise do c”, write if a; then b; else c; fi.

Common misconceptions① “A pipeline has failed, $? will be non-zero”—by default only the last stage counts. ② “Non-zero always means an error”—grep returns 1 only means no match,diff returns 1 only means there are differences. ③ “echo $? can be read twice”—after the first echo, $? is already echo's status (0). ④ “cmd | while read … variables changed inside it are visible outside”—every stage of a pipeline runs in a subshell (Module 7, Lesson 2). ⑤ “cmd || exit exits with 1”—exit used without arguments the previous command's status; here it is cmd's status (usually exactly what you want).

Pipeline: concurrent processes and the kernel buffer

grep '" 5[0-9][0-9] ' access.log | awk '{print $1}' | sort | uniq -c bash (parent) · wait for all grepfd1 → pipe A pipe A awk0 ← A · 1 → B pipe B sortreads all input before printing C uniq -cfd1 → terminal 4 processes start at the same time (one fork per stage); when the buffer is full, the writer blocks; once the reader exits, the writer receives SIGPIPE PIPESTATUS = (grep awk sort uniq), each one's status; $? = the last stage's (uniq) status, unless set -o pipefail
Figure 6-1: pipeline stages run concurrently; Bash collects each stage's status into PIPESTATUS

Short-circuit evaluation: a && b || c

a 0 (success) b 0 → skip c done (status 0) a non-zero → skip b b non-zero → c also runs! c && and || have equal precedence, left to right: ((a && b) || c) To express “do b on success, otherwise do c”, you must write if a; then b; else c; fi
Figure 6-2: evaluation paths of lists; the red path is the most common logic bug

Pipeline and short-circuit evaluation simulator

Pick a command and step through to observe which processes Bash creates, their statuses,PIPESTATUS the contents of set -o pipefail , and the results in default mode and under $? , respectively. Data comes from ~/bashlab/data/access.log (results are actual values from Bash 5.2).

Ready.
The real mechanism behind the animation Bash's execute_pipeline for each stage calls pipe() and make_child() (fork); in the child process, dup2 it connects pipe ends to fd 0/1, closes the extra ends, then runs the command; the parent closes its own pipe ends (otherwise the reader never gets EOF), then wait_for collects each child's status into PIPESTATUS. && / || In execute_connection , the shell decides whether to run the right side based on the left side's status.

Command table

Command / variablePurposeNotes
$?Status of the previous command (pipeline)Save immediately: rc=$?
"${PIPESTATUS[@]}"each stage's status of the previous foreground pipelinealso updated by a single command (it has only one element)
set -o pipefailpipeline status = the rightmost non-zero statusshopt -o pipefail View
! pipelinenegates statusdoes not affect set -e 's behavior (Lesson 4).
$! / wait [pid]PID of the most recent background job / wait for it and get its statuswait -n wait for any one (4.3+)
exit n / return nexit a script / function with status nn is 0–255
grep -qonly the status, no outputexit on the first match
cd ~/bashlab/data
grep '" 404 ' access.log | wc -l;  echo "PIPESTATUS=${PIPESTATUS[*]}"
grep 'PATCH' access.log | wc -l;   echo "PIPESTATUS=${PIPESTATUS[*]}"
cat nosuch.log | wc -l;            echo "PIPESTATUS=${PIPESTATUS[*]}"
yes | head -n1;                    echo "PIPESTATUS=${PIPESTATUS[*]}"
set -o pipefail
grep 'PATCH' access.log | wc -l;   echo "pipefail rc=$?"
yes | head -n1;                    echo "pipefail rc=$?"
set +o pipefail
9
PIPESTATUS=0 0
0
PIPESTATUS=1 0
cat: nosuch.log: No such file or directory
0
PIPESTATUS=1 0
y
PIPESTATUS=141 0
0
pipefail rc=1
y
pipefail rc=141

How to verify:echo "…${PIPESTATUS[*]}" — expansion occurs before echo runs, so it reads the value from the previous pipeline. Common mistake: First run echo $? , then read PIPESTATUS—by then it is already echo's status. Production use: Backup pipeline tar … | gzip | aws s3 cp - s3://… must check each stage, otherwise a tar failure would still upload a “successful” empty package.

grep -q POST  access.log;            echo "match=$?"
grep -q PATCH access.log;            echo "nomatch=$?"
grep -q x nosuch 2>/dev/null;        echo "error=$?"
true && false || echo "c runs"
! grep -q PATCH access.log && echo "no PATCH requests"
bash -c 'kill -TERM $$';             echo "sigterm=$?"
false; echo "$? $?"
match=0
nomatch=1
error=2
c runs
no PATCH requests
Terminated
sigterm=143
1 1

Last line: two $? in the same echo are expanded before echo runs, so both are 1.

Goal: Use a pipeline to analyze the sources of 5xx responses in access.log, and write a version that checks the status of every stage. Environment:~/bashlab/data. Cost: None.

Which IPs do the 5xx come from:
cd ~/bashlab/data
grep '" 5[0-9][0-9] ' access.log | awk '{print $1}' | sort | uniq -c | sort -rn
      7 10.20.1.31
      4 192.0.2.12
      4 10.10.1.22
      3 192.0.2.11
      2 203.0.113.99
      2 203.0.113.7
      2 198.51.100.23
      2 172.16.5.4
      2 10.10.1.21

Of 10.20.1.31's 7 requests, 4 are consecutive 502s on lines 458–461. Use | awk '{s+=$1} END{print s}' to confirm the total is 28.

Create a “silent failure”: when the log file name is wrong, the pipeline still succeeds:
grep '" 5[0-9][0-9] ' acess.log | awk '{print $1}' | sort | uniq -c; echo "rc=$? PIPESTATUS=${PIPESTATUS[*]}"
grep: acess.log: No such file or directory
rc=0 PIPESTATUS=2 0 0 0
Use pipefail to make the failure visible, and save PIPESTATUS:
top5xx() {
  local log=$1
  set -o pipefail
  grep '" 5[0-9][0-9] ' "$log" | awk '{print $1}' | sort | uniq -c | sort -rn
  local -a ps=("${PIPESTATUS[@]}"); local rc=$?
  set +o pipefail
  # grep returning 1 only means “no 5xx”, not an error
  if (( ps[0] > 1 )); then echo "grep failed (${ps[0]}) on $log" >&2; return 2; fi
  return 0
}
top5xx acess.log; echo "rc=$?"
top5xx access.log >/dev/null; echo "rc=$?"
grep: acess.log: No such file or directory
grep failed (2) on acess.log
rc=2
rc=0

Note: local -a ps=("${PIPESTATUS[@]}") must be the first command after the pipeline; whereas local rc=$? reads the previous local 's status (0)—which is why saving the array is preferred. Functions and local are covered in detail in Lesson 3.

Correct and incorrect uses of short-circuiting:
mkdir -p ~/bashlab/tmp/sc && cd ~/bashlab/tmp/sc && touch a.tmp b.tmp && ls
cd /nonexistent-dir; rm -f -- *.tmp          # dangerous: deletes in the current directory after cd fails!
cd ~/bashlab/tmp/sc && rm -f -- *.tmp && ls -A | wc -l
a.tmp  b.tmp
bash: cd: /nonexistent-dir: No such file or directory
0

In this lab, the second line “happens” to delete ~/bashlab/tmp/sc the .tmp files in that directory (because you are still there after cd fails)—in production, this is an incident. Correct forms cd "$dir" || exit or cd "$dir" && ….

Cleanup: cd ~/bashlab && rm -rf -- ~/bashlab/tmp/sc

Case 1: database backups “succeeded” for three months, all empty files

Problem:pg_dump app | gzip > /backup/app.sql.gz It ran daily with exit code 0; during a restore drill, every file was found to be only 20 bytes. Root cause: After a password rotation, pg_dump failed authentication, but the pipeline status came from gzip. Fix:set -o pipefail (or check PIPESTATUS), and after the backup, verify size / decompressibility (gzip -t), run regular restore drills (Lesson 6 opsctl backup).

Case 2: … | head fails randomly under pipefail

Problem: The CI script enables set -euo pipefail, and in it kubectl get pods -A | head -n 20 occasionally causes the whole job to fail with exit code 141. Root cause: When output exceeds the pipe buffer, head exits first and kubectl receives SIGPIPE. When output is small, kubectl finishes writing before head exits, so the failure looks “random”. Fix: write to a temp file, then head; or { kubectl … || true; } | head; or check PIPESTATUS[0] to allow 141.

Case 3: a && b || c causes duplicate alerts

Problem:check_health && send_ok_metric || send_alert: one day the metrics service went down, and send_ok_metric failed, so the healthy service also triggered an alert. Fix: Rewrite as if check_health; then send_ok_metric; else send_alert; fi; ShellCheck's SC2015 flags this pattern.

Common errors and fixes

The script exits with 0, but an intermediate command clearly reported an error

Cause: The script's exit code is the last command's status; a pipeline's status is the last stage's status.

bash -x script.sh; echo "rc=$?"

Fix: Check after critical commands || exit; enable pipefail; Lesson 4 uses strict mode.

exit code 141 (or “Broken pipe”)

Cause: The pipe being written to has no reader anymore (the downstream head, grep -q, or less exited first).

Fix: Usually harmless; under pipefail, handle 141 separately, or avoid having the upstream produce large amounts of unneeded output.

exit codes 130 / 137 / 143

Cause: 130 = SIGINT (Ctrl+C); 137 = SIGKILL (often from the OOM killer or kill -9, a container over its memory limit); 143 = SIGTERM (kill, systemd stop, Kubernetes terminating a pod).

kill -l $(( 137 - 128 ))      # KILL
journalctl -k | grep -i 'out of memory'

Fix: For 137, check memory first; for 143, check whether a scheduler or timeout terminated it; scripts can use trap for cleanup (Lesson 4).

A counter in a while loop returns to 0 after the loop ends

Cause:cmd | while read … 's while loop runs in a subshell.

Fix:while read …; done < file or done < <(cmd) (Module 7, Lesson 2).

Command-line exercise
1. Run tar -czf - ~/bashlab/data | wc -c, then print the exit codes of tar and wc separately.
tar -czf - ~/bashlab/data | wc -c; echo "tar=${PIPESTATUS[0]} wc=${PIPESTATUS[1]}"

GNU tar prints “Removing leading `/' from member names” (to stderr), but its status is still 0.

2. If access.log contains no PATCH requests, print “clean”; use only one line and do not use if.
! grep -q '"PATCH ' ~/bashlab/data/access.log && echo clean

You can also write grep -q … || echo clean, but note that clean is also printed when grep returns 2 (file error); a rigorous version needs to distinguish 1 from 2.

Scenario analysis exercise
A deployment script contains curl -fsS "$url/healthz" | grep -q ok && echo healthy || rollback. List all the ways this line can go wrong, and rewrite it.

① curl fails (connection refused, HTTP 500,-f makes HTTP errors return 22) → grep reads empty input and returns 1 → rollback; this part is as expected; ② but if curl echo healthy fails (for example, stdout is closed, which is rare), it also rolls back; ③ grep -q exits as soon as it finds a match, so curl may receive SIGPIPE, but in default mode the pipeline status comes from grep, so there is no impact; with pipefail on, it can be misjudged; ④ there is no timeout, so curl can hang. Rewrite:

if body=$(curl -fsS --max-time 5 "$url/healthz") && [[ $body == *ok* ]]; then
  echo healthy
else
  rollback
fi

Separate “fetch” from “check”: the status is clear, with no ambiguity from pipelines or short-circuiting; Lesson 6 adds retries and backoff.

Verified instructional videos

▶
Bash Scripting Tutorial for Beginners — freeCodeCamp.org
English · introductory explanation covering exit codes, conditionals and pipes
▶
you need to learn BASH Scripting RIGHT NOW!! // EP 1 — NetworkChuck
English · easygoing introduction, suitable for review

No verified video was found that specifically covers PIPESTATUS / pipefail / SIGPIPE; refer to this module's animation.

Official docs

Video storyboard script (about 90 seconds)

This lesson cannot directly generate video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Shot 1 · 0–20s
Visual: four workers (grep, awk, sort, uniq) stand in a row and start work at the same time, with a conveyor belt (pipe) in the middle.
Narration: the commands in a pipeline run at the same time, one process per segment.
Shot 2 · 20–45s
Visual: the first worker falls down (status 2), the last worker raises a green card 0, and the referee only looks at the last one.
Narration: by default, a pipeline's status only reflects the last segment, so earlier failures are swallowed.
Shot 3 · 45–70s
Visual: the PIPESTATUS scoreboard shows 2 0 0 0; after turning on the pipefail switch, the referee raises 2.
Narration: use PIPESTATUS to check each segment, and pipefail so that a failure in any segment counts as a failure.
Shot 4 · 70–90s
Visual: the fork in a && b || c, where c also runs when b fails.
Narration: chaining with && and || is not if/else; when you need branching, write an if.
or score ≥ 70% on the “Quiz”

Module 7 · Variables, Environment and Subshells

42:00 – 50:00 · Shell variables only live in the current shell; only after export do they enter the environment and get inherited by child processes; no child process (including a subshell) can change the parent's variables
8 minBash 5.3★★★★★
Learning objectives
  • Correctly assign (name=value, no spaces around the equals sign), distinguish shell variables and environment variables, and use export,export -n,declare -p,env,printenv.
  • Understand prefix assignments VAR=x cmd: passed only to that one command's environment.
  • Distinguish subshells (a forked copy of Bash that inherits all variables) and a new Bash process (via execve, inheriting only environment variables); list all syntax that creates a subshell.
  • Explain and fix “cmd | while read ” after which the counter is 0 $$,$BASHPID,$BASH_SUBSHELL,$SHLVL and common special variables.
Prerequisites: Module 1 (processes) and Module 6 (pipes). Importance:★★★★★ (prerequisite for the Lesson 2 scope animation)

What: two kinds of variables

Shell variablesEnvironment variables
Created byname=value,declare,read,forexport name / export name=value / declare -x; or inherited from the parent process
Stored inthe current shell process's memorythe process's environment block (execve the third argument of envp),/proc/PID/environ Visible to
subshells: ( ) can see?Yes (fork copies the entire memory)Yes
external commands / new Bash processes: bash can see?NoYes (a copy)
Viewdeclare -p name,setenv,printenv,declare -px
Naming conventionsLowercase: log_file,countUppercase: PATH,HOME,OPSCTL_ENV

When assigning,no spaces are allowed around the equals sign: count = 1 it is parsed as “running the command named count, with arguments = and 1” → 127. All variables are strings, unless you use declare -i (integer),-a (array),-A (associative array) and similar attributes; s=5; s+=3 yields 53,declare -i i=5; i+=3 yields 8.

Why: why can't the parent process's variables be changed

When execve runs, the environment is copied to the new program as an array of strings; afterwards parent and child are independent. A subshell is fork a full copy made by fork, also with independent memory. So: variables in a child process cd,x=5,export all disappear when the child process exits. To “return” data, only these work: stdout (v=$(cmd)),exit status,files, or simply avoid creating a subprocess (source,{ }, and Bash 5.3's ${ cmd; }).

How: which syntax creates subshells

SyntaxSubshell?Notes
( list )YesExplicit subshell: temporarily cd, temporarily change IFS / options without affecting the outside
{ list; }NoJust grouping (redirecting the whole block, with &&); { a space is required after } , and before it you need ; or a newline
$(cmd),`cmd`Yesassignments inside it can't get out
${ cmd; },${| cmd; }No (5.3+)Module 4
Pipeline segments a | bYesException: shopt -s lastpipe and job control is off (off by default in scripts), the last segment runs in the current shell
cmd &YesBackground jobs
<(cmd) / >(cmd)Yes (the cmd part)but the command that uses it runs in the current shell: while …; done < <(cmd) variables are preserved
bash script.sh,./script.shnot a subshell, but a brand-new Bash processthat inherits only environment variables

When: common special variables

VariableMeaningVariableMeaning
$0Script name / shell name$$PID of the current shell (in a subshell unchanged)
$1 … ${10}Positional parameters$BASHPIDActual PID of the current process (changes in a subshell)
$#Number of arguments$BASH_SUBSHELLSubshell nesting depth
"$@" / "$*"All arguments (individually / combined)$SHLVLBash process nesting level (+1 for each new bash started)
$? / $!Last exit status / most recent background PID$PWD $OLDPWDCurrent / previous directory
$-Current shell option flags$SECONDS $EPOCHSECONDSShell running time in seconds / Unix time (5.0+)
$_Last argument of the previous command$RANDOM $SRANDOM0–32767 pseudo-random / 32-bit strong random (5.1+)
Common misconceptions① “A subshell only inherits exported variables”—that describes a new process; ( … ) and $( … ) inherit all variables and functions. ② “After export , the child changes the value and the parent changes too”—the environment is a copy. ③ “VAR=x cmd will set VAR in the current shell”—it only sets it in the environment of cmd. ④ “source is the same as running a script”—source runs in the current shell and changes your variables and directory (Module 1). ⑤ “Uppercase variable names are more standard”—environment variables and constants are uppercase; script-internal variables are lowercase to avoid accidentally overwriting PATH,HOME,USER such system variables.

Inheritance of processes and variables

Interactive bash (PID 4100, SHLVL=1) Shell variables: x=1, function greetEnvironment variables: PATH, HOME, Y=2 (exported) ( … ) subshell (fork) x=1 ✓ Y=2 ✓ greet ✓$$=4100 (unchanged) BASHPID=4123Change x=5 → gone on exit bash -c '…' new process (fork+execve) x ✗ (not exported) Y=2 ✓ greet ✗$$=4130 · SHLVL=2Inherits only the strings in envp Z=3 ls (prefix assignment) ls environment: PATH HOME Y Z=3Z does not exist in the parent shellOften used for LC_ALL=C sort fork: copies all memory execve: passes only the environment Environment + temporary variables
Figure 7-1: a subshell inherits everything; a new process inherits only the environment; no child process can modify the parent

Data flow: why | while read the count is lost

Main shell: n=0After the loop, echo $n → 0 Child process: grep87 POST lines Subshell: while read (a copy of n)n goes from 0 up to 87, then the subshell exits → the copy is gone Fix: while read …; done < <(grep POST access.log)while runs in the main shell, only grep is in a child process → n=87 Or: shopt -s lastpipe (in a script)the last pipeline segment runs in the current shell → n=87
Figure 7-2: the core animation in Lesson 2 expands this process step by step into parameter expansion and scope

Process and environment inheritance animation

The left side is your interactive shell, and the right side is the child process it creates. Choose an action and step through it to see which variables are copied during fork / execve, and where changes made in the child end up. Initial state: x=1 (shell variables) export Y=2, function greet, current directory ~/bashlab.

Parent process: interactive bash
Child process
(not yet created)
Ready.
The real mechanism behind the animation A subshell is created by fork (Bash source make_child), the kernel shares the parent's memory copy-on-write, so all variables, functions, aliases and options are “inherited”; external commands or new Bash processes are started by execve(path, argv, envp) , whose memory is replaced entirely, so only envp (Bash builds maketemp_env/ built from exported variables NAME=value array) is passed on. $$ Keeping the top-level shell's PID inside a subshell is a POSIX requirement, so only $BASHPID is the real PID.

Command table

CommandPurposeDescription
name=valueAssignmentno spaces; quote the value if it contains spaces
export name[=value]Mark as environment variableexport -n name Unexport; export -p List
declare -p name: show attributes and values-x exported,-i integer,-r read-only,-a/-A array
env / printenv NAMEShow the environmentenv -i run with an empty environment; env NAME=v cmd
unset name / unset -f fnunset variable / functionread-only variables cannot be unset
readonly nameread-onlyConstant: readonly VERSION=0.1
( … ) / { …; }Subshell / current-shell groupingsee Principles
tr '\0' '\n' < /proc/$$/environView process at startup, its environment; later exports are not reflected here
x=1; Y=2; export Y
( echo "subshell: x=$x Y=$Y"; x=5 ); echo "after subshell x=$x"
bash -c 'echo "new bash: x=[$x] Y=[$Y]"'
Z=3 bash -c 'echo "prefix: Z=[$Z]"'; echo "parent Z=[${Z-unset}]"
declare -p x Y
export -n Y; bash -c 'echo "after export -n: Y=[$Y]"'
subshell: x=1 Y=2
after subshell x=1
new bash: x=[] Y=[2]
prefix: Z=[3]
parent Z=[unset]
declare -- x="1"
declare -x Y="2"
after export -n: Y=[]

How to verify:declare -p in the -x indicates it is exported. Common mistakes: In bash -c '…' , using unexported variables, or double quotes so the outer shell expands first (bash -c "echo $x" is expanded by the outer shell before being passed in; the result is “luckily” correct, but breaks with special characters). Production use: In CI, distinguish between “pipeline variables” and “variables exported to child processes”.

cd ~/bashlab/data
echo "BASH_SUBSHELL=$BASH_SUBSHELL"; ( echo "in ( ): $BASH_SUBSHELL"; ( echo "nested: $BASH_SUBSHELL" ) )
( [[ $$ == "$BASHPID" ]] && echo "same" || echo "sub: \$\$ unchanged, BASHPID differs" )
n=0; grep POST access.log | while read -r _; do n=$((n+1)); done; echo "pipe-while n=$n"
n=0; while read -r _; do n=$((n+1)); done < <(grep POST access.log); echo "procsub n=$n"
count = 1; echo "rc=$?"
s=5; s+=3; declare -i i=5; i+=3; echo "s=$s i=$i"
BASH_SUBSHELL=0
in ( ): 1
nested: 2
sub: $$ unchanged, BASHPID differs
pipe-while n=0
procsub n=87
bash: count: command not found
rc=127
s=53 i=8

Goal: Write an environment file for the dataset that can be source d, compare sourcing with executing it, and count prod servers in three ways to see how subshells affect variables. Environment:~/bashlab. Cost: None.

Environment file:
cat > ~/bashlab/env.sh <<'EOF'
# Usage: source ~/bashlab/env.sh
export BASHLAB_HOME="$HOME/bashlab"
export BASHLAB_DATA="$BASHLAB_HOME/data"
bashlab_greeting="hello from env.sh"      # not exported: only for the current shell
case ":$PATH:" in *":$BASHLAB_HOME/bin:"*) ;; *) PATH="$BASHLAB_HOME/bin:$PATH" ;; esac
EOF
bash ~/bashlab/env.sh;   echo "executed: [${BASHLAB_DATA-unset}]"
source ~/bashlab/env.sh; echo "sourced:  [$BASHLAB_DATA] [$bashlab_greeting]"
bash -c 'echo "child: [$BASHLAB_DATA] [${bashlab_greeting-unset}]"'
executed: [unset]
sourced:  [/home/labadmin/bashlab/data] [hello from env.sh]
child: [/home/labadmin/bashlab/data] [unset]

case ":$PATH:" form ensures that repeated source calls do not add the same directory to PATH more than once (idempotent). PATH is already an environment variable, so changes to it are exported automatically.

Count prod servers in three ways:
cd "$BASHLAB_DATA"
n=0; grep ',prod,' servers.csv | while IFS=, read -r name _; do n=$((n+1)); done; echo "1) pipe:      $n"
n=0; while IFS=, read -r name _; do n=$((n+1)); done < <(grep ',prod,' servers.csv); echo "2) procsub:   $n"
n=$(grep -c ',prod,' servers.csv); echo "3) cmd subst: $n"
1) pipe:      0
2) procsub:   6
3) cmd subst: 6

IFS=, read is a prefix assignment: it sets IFS to a comma only during this read. Lesson 2 covers read -r,IFS and mapfile in full.

Use a subshell for “temporary changes”:
( cd /tmp && IFS=: && set -f && echo "in sub: $PWD" ); echo "back in: $PWD"
LC_ALL=C sort -t, -k2,2 -k1,1 servers.csv | head -n 4
in sub: /tmp
back in: /home/labadmin/bashlab/data
api-01,dev,canadacentral,10.10.1.22,api
db-01,dev,canadacentral,10.10.1.23,db
web-01,dev,canadacentral,10.10.1.21,web
name,env,region,ip,role

Variables set in the subshell, such as cd,IFS,set -f none of them leak out. LC_ALL=C The prefix makes sort compare by bytes, so results are reproducible (the header name,env… 's second field env sorts dev after it).

Inspect the environment in /proc (Linux):
export DEMO_VAR=42
bash -c 'tr "\0" "\n" < /proc/$$/environ | grep -E "^(DEMO_VAR|BASHLAB_DATA)="'
BASHLAB_DATA=/home/labadmin/bashlab/data
DEMO_VAR=42
Clean up: unset DEMO_VAR; keep ~/bashlab/env.sh (used in Module 8).

Case 1: “I exported KUBECONFIG, why doesn't it work in another terminal?”

Problem: In one terminal, run export KUBECONFIG=~/.kube/prod, but kubectl in the other terminal still connects to the dev cluster. Root cause: Environment variables are only passed to child processes; the two terminals are sibling processes. Fix: Source an environment file in each shell as needed, or use the tool's own context mechanism (kubectl config use-context). The more dangerous mistake is forgetting that a terminal still points to prod: show the current environment in the prompt via PS1 .

Case 2: a script overwrote a system variable

Problem: In the script, setting PATH=$(dirname "$0")/build (the author meant to store a “build path”) so every command after it fails with 127. Another case is USER=deploy changing the behavior of downstream tools. Fix: Use lowercase for script-internal variables (build_path), and use uppercase with a project prefix only for variables that need exporting (OPSCTL_ENV), which is also the recommendation of the Google Shell Style Guide (Lesson 7).

Case 3: sudo Losing environment variables

Problem:export HTTPS_PROXY=…; sudo apt update Requests do not go through the proxy. Root cause: sudo resets the environment by default (env_reset), keeping only whitelisted variables. Fix:sudo --preserve-env=HTTPS_PROXY,HTTP_PROXY apt update, or configure the proxy in /etc/apt/apt.conf.d/ . Note that Ubuntu 26.04's sudo-rs and traditional sudo may handle environment details differently, so sudo env verify by testing.

Common errors and fixes

bash: count: command not found (you wrote count = 1)

Cause: The assignment has spaces around the equals sign.

Fix:count=1; for arithmetic, use (( count = 1 )) (spaces are allowed inside double parentheses).

A variable accumulated in a loop is 0 / empty outside the loop

Cause: The loop is in a pipeline (subshell).

n=0; printf '1\n2\n' | while read -r l; do n=$((n+1)); echo "inside BASHPID=$BASHPID"; done; echo "outside BASHPID=$BASHPID n=$n"

Fix:done < file,done < <(cmd), or in a script, shopt -s lastpipe.

Variables you just set are not visible in a child process

Cause: The variable was not exported.

declare -p VAR      # without -x it is not passed to child processes

Fix:export VAR, or for just one command: VAR=value cmd.

bash: VERSION: readonly variable

Cause: Assigning to a read-only variable (common when a library defining readonly is sourced twice). In a non-interactive shell, this makes the script exit.

Fix: In the library file, use a “define once” guard: [[ -v OPSCTL_LIB_LOADED ]] && return; readonly OPSCTL_LIB_LOADED=1 (Lesson 3).

Command-line task
1. In one command line, without changing the current directory, print /etc — the number of files under it.
( cd /etc && ls -A | wc -l ); pwd

A cd inside a subshell does not affect the outer shell.

2. Only for one sort call, set LC_ALL=C, and prove that the current shell's LC_ALL has not changed.
LC_ALL=C sort ~/bashlab/data/servers.csv | head -n2; echo "LC_ALL=[${LC_ALL-unset}]"
Scenario analysis
A function get_token() { TOKEN=$(curl -s …); } is called like this: get_token | tee -a token.log, and afterwards $TOKEN is empty. Another spot t=$(get_token) also gets no value. Explain why, and give two correct ways to write it.

First call: the function runs inside a pipeline, in a subshell,TOKEN so the variable is set only in the subshell's copy. Second case: $( ) also a subshell, and the function itself prints nothing to stdout, so t is empty. Correct approaches: ① call it directly get_token (not in a pipeline), then use $TOKEN; ② have the function print the value: get_token() { curl -s …; }; TOKEN=$(get_token); ③ Bash 5.3 supports get_token() { REPLY=$(curl -s …); }; TOKEN=${| get_token; }. Note: do not log the token itself.

Verified teaching videos

▶
Bash Scripting Full Course 3 Hours — linuxhint
English · chapters on variables, environment variables and script basics
▶
Lecture 2: Shell Tools and Scripting (2020) — Missing Semester
English · variables, special variables $0 $# $? $$ and command substitution

No verified video specifically covering “subshells and environment inheritance” was found; refer to this module's animation instead.

Official documentation

Video storyboard script (about 90 seconds)

This lesson cannot directly generate video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Shot 1 · 0–20s
Visual: the parent shell's backpack has two pockets: a private pocket (x=1) and a public pocket (export Y=2).
Narration: there are two kinds of variables; only environment variables put in the public pocket are handed to the new program.
Shot 2 · 20–45s
Visual: fork copies a complete backpack (the subshell), while execve copies only the public pocket (the new process).
Narration: a subshell inherits everything; a new process inherits only the environment.
Shot 3 · 45–70s
Visual: the while loop on the right side of the pipe counts up to 87 on the copy, then the copy is eaten by a shredder, and the parent shell still shows 0.
Narration: a loop in a pipeline runs in a subshell, so its count disappears with it.
Shot 4 · 70–90s
Visual: changed to done < <(grep …), and the count stays in the parent shell.
Narration: keep the loop in the current shell, and feed it data with process substitution or redirection.
or score ≥ 70% on the “Quiz”

Module 8 · Your first script: from the command line to an executable file

50:00 – 60:00 · Bring the first 7 modules together: shebang, permissions, PATH, arguments, stdout / stderr, exit codes, syntax checking and trace debugging, and write ~/bashlab/bin/datainfo
10 minBash 5.3an interactive troubleshooting tree★★★★★
Learning objectives
  • Write a well-structured script: shebang → header comments (purpose, usage, exit codes) → functions → argument checks → main logic → explicit exit.
  • Use positional parameters correctly: $1,$#,"$@" (and why not to use $*), write data to stdout and errors to stderr, and follow the opsctl exit code convention (0 / 1 / 2 / 3).
  • Make the script run “like a command”: chmod +x, put it in the ~/bashlab/bin directory on PATH, understand how the kernel starts the interpreter via shebang, and how Bash reads and executes the script line by line.
  • Use bash -n (syntax check),bash -x / set -x + PS4 (trace) debugging, and use the interactive troubleshooting tree to find common causes of “the script won't run”.
Prerequisites: Modules 1–7. Importance:★★★★★

What: the skeleton of a well-structured script

#!/usr/bin/env bash
# datainfo — show the line and byte counts of data files
# Usage: datainfo [-h] FILE...
# Exit codes: 0 success; 1 a file could not be read; 2 usage error
usage() { printf 'Usage: %s [-h] FILE...\n' "${0##*/}"; }

if [[ $# -eq 0 ]]; then usage >&2; exit 2; fi
if [[ $1 == -h || $1 == --help ]]; then usage; exit 0; fi

rc=0
for f in "$@"; do
  if [[ ! -f $f || ! -r $f ]]; then
    printf 'datainfo: cannot read: %s\n' "$f" >&2
    rc=1
    continue
  fi
  lines=$(wc -l < "$f")
  bytes=$(wc -c < "$f")
  printf '%-16s %6d lines %8d bytes\n' "${f##*/}" "$lines" "$bytes"
done
exit "$rc"
PartCorresponding moduleKey points
#!/usr/bin/env bashModule 1The kernel reads it; find bash via PATH
Header comments—Purpose, usage, exit codes: others (and you three months from now) can use the script just by reading these lines
usage() FunctionsModule 2Functions are commands in the current shell; ${0##*/} get the script name (parameter expansion, Lesson 2)
[[ $# -eq 0 ]]Modules 2, 4[[ is a keyword; not split internally
usage >&2; exit 2Modules 5, 6usage errors go to stderr with exit code 2; -h when successful, write to stdout with exit code 0
for f in "$@"Modules 3, 4"$@" keep each argument intact (including spaces and newlines)
wc -l < "$f"Module 5input redirection: wc outputs only the number
exit "$rc"Module 6partial failure must also be reflected in the exit code, not “the last command happened to succeed”

Why: why write a script instead of a long command

  • Reusable, reviewable: scripts can go into Git, undergo code review, be checked by ShellCheck, and be tested with bats (Lesson 7).
  • Composable: follow the convention “data → stdout, diagnostics → stderr, success or failure → exit code”, and the script can work like grep in pipes,&& chains and CI pipelines.
  • Predictable environment: scripts are non-interactive and do not depend on your .bashrc, aliases and current directory (Module 1).

How: what happens when ./datainfo access.log is run

  1. the interactive shell parses and expands (Module 4); when the command name contains /, skip the lookup; fork a child process.
  2. Child process execve("./datainfo", ["./datainfo","access.log"], envp). The kernel checks the x permission and reads #!/usr/bin/env bash, and runs instead /usr/bin/env bash ./datainfo access.log.
  3. env Find bash in PATH and execve; the new Bash process starts in non-interactive mode (does not read .bashrc),$0=./datainfo,$1=access.log.
  4. Bash Line by line: read the script: read one complete command → parse → expand → execute, then read the next. This means syntax errors in the second half are only found when execution reaches them (so you should bash -n), and also means editing the script while it runs can cause strange behavior.
  5. Execution reaches exit "$rc" (or the end of the file, with the status of the last command), the process ends; the parent shell's $? gets this value.

When: choosing how to run it and where to store it

NeedApproach
Personal utility~/bashlab/bin (this lesson) or ~/.local/bin, add to PATH
Project scriptsPut them in the repository's scripts/ or bin/, and call them with a relative path: ./scripts/build.sh; save the x bit in Git (git update-index --chmod=+x)
Needs to modify the current shell (variables, directory)Write it as a file to be source d (Module 7's env.sh); do not add the x bit
Ops tool with multiple subcommandsThe opsctl structure from Lesson 3: bin/opsctl + lib/*.sh
Complex logic (mainly data structures, concurrency, JSON processing)Consider Python / Go; for bulk host configuration, consider Ansible
Common misconceptions① “$* and $@ are the same”—only quoted "$@" can pass each argument through unchanged. ② “A script without a final exit has exit code 0”—it is the status of the last command. ③ “Adding set -x is enough”—bash -n can catch syntax errors before running; set -x ④ “It is enough to echo error messages”—they should go to stderr (>&2), otherwise they get mixed into downstream data. ⑤ “Script file names must end in .sh”—commands put in PATH usually have no extension (datainfo), the extension has nothing to do with executability; but library files in the repo use .sh so that tools can recognize them.

Script lifeline: from ./datainfo to $?

Interactive bashParse · expandcontains / → no PATH lookup fork child process execve"./datainfo" argv envpno x bit → 126 kernel binfmt_scriptreads #!/usr/bin/env bashinterpreter missing → ENOENT envfind bash in PATHexecve bash bash (non-interactive)$0=./datainfo$1=access.log read and execute the script line by line read one complete command → the Module 4 pipeline (expand → redirect → look up → execute) → read the next external commands such as wc are then fork + execve; printf and [[ ]] run in this process syntax errors later in the file are only reported when execution reaches them → run bash -n first exit "$rc"→ parent process waits$? = 0 / 1 / 2 Compare: bash datainfo … skips the execve-of-script and shebang steps (no x bit needed); source datainfo runs line by line inside the current shell (exit would close your terminal!) stdout → data (can go into a pipe); stderr → diagnostics (shown in the terminal or written to a log); exit code → success or failure (used by && / if / CI checks)
Figure 8-1: a script is also “one command”; it goes through all the stages of the Module 4 pipeline, then repeats this pipeline for each line in a new Bash

Convention for the three output channels

datainfoone file unreadable, the rest fine stdout (fd 1)access.log 611 lines … stderr (fd 2)cannot read: nosuch.log exit code 10 success, 1 error, 2 usage, 3 dependency the whole opsctl series follows the same convention: log::info/warn/error write to stderr, util::die exits with a non-zero code
Figure 8-2: data, diagnostics and success/failure channels do not mix

Script execution path animation

Choose a way to run it or a “broken” script, and step through the handoffs between Bash, the kernel and the interpreter to see where it fails and what the exit code is.

Ready.
The real mechanism behind the animation The kernel, inside execve , uses binfmt_script to handle it #!: it parses the interpreter path and one optional argument, appends the script path to the argument list, and re-executes the interpreter (see the “Interpreter scripts” section of execve(2)). Bash reads the script using buffered input and parses and executes it one command at a time (reader_loop); when it encounters exit built-in, it calls exit_shell. source Executing the file's content in the current shell, any exit will make the current shell exit; for an interactive terminal, that means closing the window.

Command table

CommandPurposeNotes
chmod +x file / chmod u+xAdd execute permissionls -l appears in x
bash -n scriptparses only, does not execute (syntax check)the cheapest check in CI; add ShellCheck in Lesson 7
bash -x script argsTrace execution:is equivalent to putting it at the top of the script set -x
PS4='+ ${BASH_SOURCE##*/}:${LINENO}: '; trace output includes file name and line numberuse single quotes so it expands at print time
"$@" / $# / $1all arguments / count / first oneshift shift arguments left (getopts, Lesson 2)
>&2write to stderrerrors and logs
exit nexit with status n0 / 1 / 2 / 3 convention
file script / cat -A script | headcheck for CRLF and BOMline endings show as ^M$ , i.e. CRLF
chmod +x ~/bashlab/bin/datainfo
source ~/bashlab/env.sh                   # make sure ~/bashlab/bin is in PATH (Module 7)
cd ~/bashlab/data
datainfo; echo "rc=$?"
datainfo -h; echo "rc=$?"
datainfo access.log servers.csv inventory.json config.yaml; echo "rc=$?"
datainfo access.log nosuch.log "files/report 2026.txt" files/-n; echo "rc=$?"
Usage: datainfo [-h] FILE...
rc=2
Usage: datainfo [-h] FILE...
rc=0
access.log          611 lines    79109 bytes
servers.csv          13 lines      526 bytes
inventory.json       14 lines     1199 bytes
config.yaml          31 lines      787 bytes
rc=0
access.log          611 lines    79109 bytes
datainfo: cannot read: nosuch.log
report 2026.txt       1 lines        8 bytes
-n                    1 lines        8 bytes
rc=1

How to verify:datainfo … 2>/dev/null only data lines remain; datainfo … >/dev/null only error lines remain. Common mistakes:for f in $@ (without quotes) will split files/report 2026.txt into two arguments. Production use: This skeleton (usage, argument checks, stderr, exit codes) is the template for every opsctl subcommand from Lesson 3.

PS4='+ ${BASH_SOURCE##*/}:${LINENO}: ' bash -x ~/bashlab/bin/datainfo servers.csv 2>&1 | head -n 8
printf 'if true; then\n  echo hi\n' > ~/bashlab/tmp/broken.sh
bash -n ~/bashlab/tmp/broken.sh; echo "rc=$?"

When running as root, Bash does not import PS4, prefix assignments have no effect, and trace lines show only + , with no file name or line number; run as a regular user.

+ datainfo:7: [[ 1 -eq 0 ]]
+ datainfo:8: [[ servers.csv == -h ]]
+ datainfo:8: [[ servers.csv == --help ]]
+ datainfo:10: rc=0
+ datainfo:11: for f in "$@"
+ datainfo:12: [[ ! -f servers.csv ]]
+ datainfo:12: [[ ! -r servers.csv ]]
++ datainfo:17: wc -l
/home/labadmin/bashlab/tmp/broken.sh: line 3: syntax error: unexpected end of file
rc=2

Goal: Rewrite the placeholder script from Module 2 as a complete datainfo, add it to PATH, test all exit codes, and check its robustness against files/ (odd file names). Environment:~/bashlab. Cost: None.

Write the script (quote the here-doc delimiter so the content is written as-is):
cat > ~/bashlab/bin/datainfo <<'EOF'
#!/usr/bin/env bash
# datainfo — show the line and byte counts of data files
# Usage: datainfo [-h] FILE...
# Exit codes: 0 success; 1 a file could not be read; 2 usage error
usage() { printf 'Usage: %s [-h] FILE...\n' "${0##*/}"; }

if [[ $# -eq 0 ]]; then usage >&2; exit 2; fi
if [[ $1 == -h || $1 == --help ]]; then usage; exit 0; fi

rc=0
for f in "$@"; do
  if [[ ! -f $f || ! -r $f ]]; then
    printf 'datainfo: cannot read: %s\n' "$f" >&2
    rc=1
    continue
  fi
  lines=$(wc -l < "$f")
  bytes=$(wc -c < "$f")
  printf '%-16s %6d lines %8d bytes\n' "${f##*/}" "$lines" "$bytes"
done
exit "$rc"
EOF
chmod +x ~/bashlab/bin/datainfo
bash -n ~/bashlab/bin/datainfo && echo "syntax ok"
hash -r; type -a datainfo
syntax ok
datainfo is /home/labadmin/bashlab/bin/datainfo
Test with odd names:
cd ~/bashlab/data
datainfo files/* 2>&1; echo "rc=$?"
--verbose.log         1 lines        8 bytes
-n                    1 lines        8 bytes
[draft] notes.md      1 lines        8 bytes
café-ünïcode.txt      1 lines        9 bytes
it's.txt              1 lines        9 bytes
line1
line2.txt       1 lines        8 bytes
price $5.txt          1 lines        8 bytes
report 2026.txt       1 lines        8 bytes
say "hi".txt          1 lines        9 bytes
star*.txt             1 lines        8 bytes
datainfo: cannot read: files/sub dir
tab	here.txt          1 lines        8 bytes
trailing-space.txt       1 lines        9 bytes
two  spaces.txt       1 lines        8 bytes
rc=1

Every odd name is handled correctly (including -n, newlines, asterisks); the directory sub dir is reported as unreadable, exit code 1. Two visible flaws are left for you to consider: ① names containing newlines split the output into two lines; machine-readable output should use %q or NUL separators (Lesson 5); ② printf %-16s aligns by bytes, so café-ünïcode.txt — multibyte characters in it misalign the columns.

Separate data and diagnostics:
datainfo access.log nosuch.log 2>/dev/null | awk '{s+=$4} END {print "total bytes:", s}'
datainfo access.log nosuch.log >/dev/null; echo "rc=$?"
total bytes: 79109
datainfo: cannot read: nosuch.log
rc=1
Experience the CRLF problem (on Linux / WSL / macOS):
printf '#!/usr/bin/env bash\r\necho hi\r\n' > ~/bashlab/tmp/crlf.sh && chmod +x ~/bashlab/tmp/crlf.sh
~/bashlab/tmp/crlf.sh; echo "rc=$?"
file ~/bashlab/tmp/crlf.sh
sed -i 's/\r$//' ~/bashlab/tmp/crlf.sh && ~/bashlab/tmp/crlf.sh
/usr/bin/env: 'bash\r': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
rc=127
/home/labadmin/bashlab/tmp/crlf.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
hi

The second line is an extra hint from newer GNU env (older versions or other env implementations may not print it). Git Bash on Windows tolerates CRLF, so you won't see this error there; this is one source of “it works on my machine, but not on the server.” macOS's sed needs sed -i '' ….

Clean up: rm -f -- ~/bashlab/tmp/{crlf,broken}.sh; keep ~/bashlab/bin/datainfo and ~/bashlab/env.sh (still used in Lesson 2).

Case 1: a script was updated while running and executed “half-new, half-old” code

Problem: A long-running deploy script was git pull updated, then reported bizarre syntax errors and even ran the wrong branch. Root cause: Bash reads subsequent commands from the file on demand; after the file changes, the read offset lands in the middle of the new file. Fix: Copy the whole script to a new path before running it during deployment (atomic replacement: write a temp file, then mv, as in the Lesson 6 release directory + symlink switch); or wrap the script body in main() { …; }; main "$@" — Bash must read the full function definition before it starts executing.

Case 2: a “green” build in CI actually failed

Problem: The last line of the build script is echo "build finished", but the earlier make failed, yet CI shows success. Fix: After critical steps, add || exit, or use the strict mode from Lesson 4; in CI, run bash -n and ShellCheck; end the script with an explicit exit "$rc" at the end.

Case 3: usage errors and runtime errors use different exit codes

Problem: The automation platform treats every non-zero exit as “retry needed”, so tasks with wrong arguments are retried endlessly. Fix: Adopt a unified convention (opsctl: 1 general error, 2 usage error, 3 missing dependency); the platform retries only on 1 and sends direct alerts to humans for 2 / 3. This is also grep (0/1/2),curl (dozens of exit codes) and similar tools' design approach.

Interactive troubleshooting tree: my script won't run

Common errors and fixes

bash: ./datainfo: Permission denied (126)

Cause: No x bit, or the filesystem is mounted with noexec (on some systems, the /tmp, on WSL, the /mnt/c depending on configuration).

ls -l datainfo; findmnt -T datainfo -o TARGET,OPTIONS

Fix:chmod +x datainfo; with noexec, run it with bash datainfo or move it to another directory.

/usr/bin/env: 'bash\r': No such file or directory

Cause: CRLF line endings.

Fix:sed -i 's/\r$//' datainfo; add to the repo .gitattributes: * text=auto eol=lf.

line N: syntax error: unexpected end of file

Cause: Missing fi / done / esac / }, or unpaired quotes, or a here-doc end marker that is not flush left. The reported line number points to the end of the file, but the real problem is earlier.

bash -n datainfo
grep -nE '^\s*(if|then|fi|for|while|do|done|case|esac)\b' datainfo

Fix: Complete the structure; use an editor that highlights matching pairs; after formatting consistently with shfmt in Lesson 7, the problem is easier to spot.

datainfo: command not found (the file is clearly in ~/bashlab/bin)

Cause: the directory is not in the current shell's PATH (a newly opened terminal did not source env.sh), or the command hash table cache is involved.

echo "$PATH" | tr ':' '\n' | grep -n bashlab; type -a datainfo

Fix:source ~/bashlab/env.sh; to make it permanent, put ~/.profile or ~/.bashrc; hash -r.

Command-line tasks
1. Write a minimal script argdump: print the argument count and each argument on its own line (wrapped in < > ), and test with argdump "a b" c .
cat > ~/bashlab/bin/argdump <<'EOF'
#!/usr/bin/env bash
printf '%d args\n' "$#"
printf '<%s>\n' "$@"
EOF
chmod +x ~/bashlab/bin/argdump && argdump "a b" c

Output 2 args,<a b>,<c>. It is the script version of the Module 3 args function, useful any time you debug quoting issues.

2. Without running datainfo, check it for syntax errors and show which interpreter will execute it.
bash -n ~/bashlab/bin/datainfo && head -n1 ~/bashlab/bin/datainfo && command -v bash
Scenario analysis
A colleague wrote cleanup.sh, whose content is cd $1; rm -rf *, and runs it in cron as cleanup.sh /data/tmp . Point out at least four problems and provide an improved version.

① $1 unquoted, so a path containing spaces is split; ② no check whether the argument is empty: cleanup.sh With no arguments, cd it cds to the home directory and deletes everything in it; ③ cd keeps running after a failure rm -rf * (in cron's working directory, usually the home directory); ④ * encounters filenames starting with - are treated as options; ⑤ no shebang, no logging, and no meaningful exit codes. Improved version:

#!/usr/bin/env bash
# cleanup.sh DIR — delete all contents under DIR (DIR must be under /data/tmp)
dir=${1:?usage: cleanup.sh DIR}
[[ $dir == /data/tmp || $dir == /data/tmp/* ]] || { echo "refuse: $dir" >&2; exit 2; }
cd -- "$dir" || exit 1
find . -mindepth 1 -delete || exit 1
echo "cleaned $dir" >&2

Lesson 4 adds set -euo pipefail,trap and logging functions.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 1 - Introduction) — Learn Linux TV
English · first script, chmod, shebang series episode 1
▶
Shell Scripting - Introduction & Shebang — HackerSploit
English · shebang and ways to run scripts
▶
you need to learn BASH Scripting RIGHT NOW!! // EP 1 — NetworkChuck
English · writing your first script hands-on

Official documentation

Video storyboard script (about 2 minutes)

This lesson cannot directly generate video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Shot 1 · 0–25s
Visual: a command in the terminal keeps growing and is “cut” into an editor, with #!/usr/bin/env bash added at the top.
Narration: when a command is worth reusing, turn it into a script.
Shot 2 · 25–55s
Visual: chmod +x then run it: the kernel reads the #! line, passes it to env, then to bash.
Narration: with execute permission and a shebang, the script runs like any ordinary command.
Shot 3 · 55–90s
Visual: three output pipes labeled stdout for data, stderr for diagnostics, and exit code for success or failure.
Narration: write data to standard output, errors to standard error, and leave success or failure to the exit code.
Shot 4 · 90–120s
Visual: bash -n catches the missing fi; bash -x shows a trace with line numbers.
Narration: first check syntax with bash -n, then use bash -x to see what each step looks like after expansion.
or score ≥ 70% on the “Quiz”

Command cheat sheet

All Lesson 1 key points: shell types, command types, quoting, expansion, redirection, pipes and exit status, variables and subshells, script skeleton
Bash 5.3Copyable

1. Shell types and startup files

echo "$-"                    # contains i = interactive
shopt -q login_shell && echo login
echo "$0" "$BASH_VERSION"
bash --noprofile --norc      # clean interactive shell
bash -lc 'cmd'               # login-style execution (reads profile)
# Login: /etc/profile → ~/.bash_profile | ~/.bash_login | ~/.profile
# interactive non-login: ~/.bashrc     non-interactive: $BASH_ENV
readlink -f /bin/sh          # Ubuntu: dash

2. Command types and lookup

type -a name                 # all identities; the first line is what actually runs
type -t name                 # alias|keyword|function|builtin|file
command -v jq >/dev/null || exit 3   # check for a dependency in a script
command ls                   # bypass aliases and functions
\ls                          # bypass aliases only
builtin cd "$d"              # use only the builtin
hash -r                      # clear the path cache
compgen -k; compgen -b       # keyword / builtin lists

3. Quoting

'literal $HOME `x` \n'           # single quotes: everything is literal
"value $HOME $(date +%F)"        # double quotes: expands, but no word splitting or globbing
$'tab\tnewline\nsingle quote\''         # ANSI-C
'it'\''s'                     # single quote inside single quotes
printf '<%s>\n' "$@"          # see argument boundaries
printf '%q\n' "$f"; echo "${f@Q}"
cmd -- "$f"; for f in ./*; do …; done

4. Seven-step expansion

# brace → tilde/parameter/command substitution/arithmetic (left to right) → word splitting → pathname → quote removal
echo {a,b}{1,2} {01..05} x{,.bak}
echo ~ ~/bin "~"              # only an unquoted leading ~ is expanded
echo $(( 3 * 4 )) "$(cmd)"
set -x; …; set +x             # see the commands after expansion
shopt -s nullglob failglob dotglob globstar
${ cmd; }  ${| cmd; }         # Bash 5.3: command substitution without fork

5. Redirection

cmd > f 2>&1     # both go to f (order matters!)
cmd &> f          # Bash shorthand
cmd 2>&1 >/dev/null | grep x   # send only stderr into the pipe
cmd |& less       # = 2>&1 |
wc -l < file      # prints no file name
cat <<'EOF' … EOF # body is not expanded; <<- strips leading tabs
tr a-z A-Z <<< "$s"
exec >>"$log" 2>&1               # send the whole script's output to the log
exec {fd}>"$f"; echo x >&"$fd"; exec {fd}>&-
echo x | sudo tee /etc/f >/dev/null

6. Pipes and exit status

echo $?                       # 0 success 1 general 2 usage 126 not executable 127 not found 128+N signal
a | b | c; echo "${PIPESTATUS[@]}"
set -o pipefail               # any segment failing means failure (note 141 = SIGPIPE)
a && b                        # b runs only if a succeeds
a || b                        # b runs only if a fails
if a; then b; else c; fi      # do not use a && b || c
! grep -q x f && echo absent
cmd & pid=$!; wait "$pid"; echo $?

7. Variables, environment and subshells

name=value                    # no spaces around the equals sign
export NAME=value; export -n NAME
declare -p name; env; printenv NAME
VAR=x cmd                     # only for cmd
( cd /tmp; … )                # subshell: does not affect the outside
{ a; b; } > f                 # grouping in the current shell
while read -r l; do …; done < <(cmd)   # keeps loop variables
echo "$$ $BASHPID $BASH_SUBSHELL $SHLVL"
source ~/bashlab/env.sh

8. Script skeleton

#!/usr/bin/env bash
# name — purpose
# Usage: name [-h] ARG...
# Exit codes: 0 success 1 error 2 usage 3 missing dependency
usage() { printf 'Usage: %s [-h] ARG...\n' "${0##*/}"; }
[[ $# -gt 0 ]] || { usage >&2; exit 2; }
for a in "$@"; do …; done
exit "$rc"
# chmod +x name; bash -n name; bash -x name args

Quick troubleshooting table

Symptom / errorMost likely causeFirst diagnostic stepFix
command not found (127)typo, PATH, environment not sourced, non-interactive shell has no aliasestype -a x; echo "$PATH"absolute path / fix PATH / use a function instead of an alias
Permission denied (126)no x bit, noexec mountls -l; findmnt -T .chmod +x or bash script
'bash\r': No such file / $'\r': command not foundCRLF line endingsfile scriptsed -i 's/\r$//'
[: too many arguments / unary operator expectedunquoted variableprintf '<%s>\n' $v"$v" or [[ ]]
ambiguous redirectredirect target is empty or contains spacesdeclare -p out> "$out"
error did not reach the log file2>&1 placed > f before itcheck redirection order> f 2>&1
pipeline failed but $? is 0only the last segment is checkedecho "${PIPESTATUS[@]}"set -o pipefail
counter is 0 after the loop| while loop runs in a subshellecho $BASHPID Comparedone < <(cmd)
child process cannot see the variablenot exporteddeclare -p VARexport VAR or VAR=x cmd
{1..$n} not expandedbrace expansion happens before parameter expansionset -xfor ((i=1;i<=n;i++))
unexpected end of filemissing fi/done/quotes; here-doc end marker not flush leftbash -ncomplete the structure

Recommended configuration snippets

~/.bashrc (interactive)

# non-interactive shells return immediately (safe for scp / rsync)
[[ $- == *i* ]] || return
HISTCONTROL=ignoreboth
HISTSIZE=10000
shopt -s histappend checkwinsize checkhash
alias ll='ls -l'               # aliases are for interactive use only
PS1='\u@\h:\w\$ '

~/.profile (login) and .gitattributes

# ~/.profile: put PATH and other environment variables here
case ":$PATH:" in *":$HOME/bashlab/bin:"*) ;; *) PATH="$HOME/bashlab/bin:$PATH" ;; esac
export PATH
[ -n "$BASH_VERSION" ] && [ -f "$HOME/.bashrc" ] && . "$HOME/.bashrc"

# repo-root .gitattributes: scripts always use LF
*.sh text eol=lf
bin/* text eol=lf

Integrated lab + final quiz

Write ~/bashlab/dataset-check.sh: validate the dataset generated by make-data.sh, safely traverse files with odd names, separate data from diagnostics, write an audit log via a custom fd, and return meaningful exit codes
about 25 minLocal onlyIntegrated M1–M8

Scenario

Lessons 2–8 all depend on ~/bashlab/data. You need to write a “dataset health check” script to run before each lesson: exit 0 when all checks pass; when any check fails, print FAIL and exit 1; exit 2 on argument errors; exit 3 when a dependency is missing (opsctl convention). Write the expected and actual value for each check to ~/bashlab/tmp/dataset-check.log.

Skeleton: shebang, header comments, argument and dependency checks (M1, M2, M8)
cat > ~/bashlab/dataset-check.sh <<'EOF'
#!/usr/bin/env bash
# dataset-check.sh — check whether the dataset generated by make-data.sh is complete
# Usage: dataset-check.sh [DATA_DIR]        default ~/bashlab/data
# Exit codes: 0 all passed; 1 some check failed; 2 usage error; 3 missing dependency
data=${1:-$HOME/bashlab/data}
log=$HOME/bashlab/tmp/dataset-check.log
fail=0

for c in wc grep cksum date; do
  command -v "$c" >/dev/null 2>&1 || { echo "dataset-check: missing command: $c" >&2; exit 3; }
done
if [[ ! -d $data ]]; then
  printf 'Usage: %s [DATA_DIR]\n' "${0##*/}" >&2
  exit 2
fi
EOF
Audit log: open once with fd 3, write many times (M5)
cat >> ~/bashlab/dataset-check.sh <<'EOF'

mkdir -p -- "${log%/*}"
exec 3>>"$log"                                   # fd 3: audit log
note() { printf '%s %s\n' "$(date +%Y-%m-%dT%H:%M:%S)" "$*" >&3; }

check() {                                        # check description expected actual
  if [[ $2 == "$3" ]]; then
    printf 'PASS  %s\n' "$1"
  else
    printf 'FAIL  %s (want %s, got %s)\n' "$1" "$2" "$3"
    fail=1
  fi
  note "$1 want=[$2] got=[$3]"
}
EOF

[[ $2 == "$3" ]]: quoting the right side makes it a literal comparison (without quotes it is pattern matching, and * in the expected value would be treated as a wildcard). ${log%/*} Remove the last / and everything after it to get the directory (Lesson 2).

Six checks (M3, M4, M6, M7)
cat >> ~/bashlab/dataset-check.sh <<'EOF'

check "access.log lines"   611  "$(( $(wc -l < "$data/access.log") ))"
check "access.log 5xx"     28   "$(grep -c '" 5[0-9][0-9] ' "$data/access.log")"
read -r header < "$data/servers.csv"
check "servers.csv header" "name,env,region,ip,role" "$header"
check "prod servers"       6    "$(grep -c ',prod,' "$data/servers.csv")"

n=0
for f in "$data"/files/* "$data"/files/.[!.]*; do
  [[ -f $f ]] && n=$(( n + 1 ))
done
check "regular files in files/" 14 "$n"

read -r sum size _ < <(cksum "$data/access.log")
check "access.log cksum" "80306651 79109" "$sum $size"

exec 3>&-
if (( fail )); then echo "dataset-check: FAILED (details: $log)" >&2; else echo "dataset-check: all checks passed" >&2; fi
exit "$fail"
EOF
chmod +x ~/bashlab/dataset-check.sh && bash -n ~/bashlab/dataset-check.sh && echo "syntax ok"

Key points: $(( $(wc -l < f) )) Use arithmetic expansion to strip leading spaces from macOS wc output; "$data"/files/* — quote variables, keep wildcards outside quotes; read … < <(cksum …) Use process substitution so that sum / size stays in the current shell (M7); for the loop is not in a pipeline, so n can accumulate.

Run: all checks pass
cd ~/bashlab && ./dataset-check.sh; echo "rc=$?"
PASS  access.log lines
PASS  access.log 5xx
PASS  servers.csv header
PASS  prod servers
PASS  regular files in files/
PASS  access.log cksum
dataset-check: all checks passed
rc=0
Create a fault: delete one 502 record
cp -r ~/bashlab/data ~/bashlab/tmp/data-broken
sed -i '458d' ~/bashlab/tmp/data-broken/access.log          # macOS: sed -i '' '458d' …
./dataset-check.sh ~/bashlab/tmp/data-broken; echo "rc=$?"
./dataset-check.sh ~/bashlab/tmp/data-broken 2>/dev/null | grep -c FAIL
FAIL  access.log lines (want 611, got 610)
FAIL  access.log 5xx (want 28, got 27)
PASS  servers.csv header
PASS  prod servers
PASS  regular files in files/
FAIL  access.log cksum (want 80306651 79109, got 2281393197 79012)
dataset-check: FAILED (details: /home/labadmin/bashlab/tmp/dataset-check.log)
rc=1
3

The second command verifies “data → stdout, diagnostics → stderr”: after discarding stderr, downstream can still reliably count FAIL lines.

Usage errors and missing dependencies
./dataset-check.sh /nonexistent; echo "rc=$?"
PATH=/nonexistent /bin/bash ./dataset-check.sh; echo "rc=$?"
tail -n 3 ~/bashlab/tmp/dataset-check.log
Usage: dataset-check.sh [DATA_DIR]
rc=2
dataset-check: missing command: wc
rc=3
2026-11-17T10:42:07 prod servers want=[6] got=[6]
2026-11-17T10:42:07 regular files in files/ want=[14] got=[14]
2026-11-17T10:42:07 access.log cksum want=[80306651 79109] got=[2281393197 79012]

PATH=/nonexistent /bin/bash …: a prefix assignment only affects this one run (M7); if you start bash by absolute path, the script's command -v wc can no longer find external commands (command is a builtin and is not affected).

Trace a run (M4, M8)
PS4='+ ${LINENO}: ' bash -x ./dataset-check.sh 2>&1 | grep -m 3 -E "(check|note) 'access"
+ 31: check 'access.log lines' 611 611
+ 28: note 'access.log lines want=[611] got=[611]'
+ 32: check 'access.log 5xx' 28 28

xtrace shows after expansion's arguments: $(( $(wc -l …) )) is now 611. The line number depends on your file contents; when running as root, Bash ignores the environment's PS4, so line numbers will not appear.

Clean up: rm -rf -- ~/bashlab/tmp/data-broken; keep dataset-check.sh, run once before each lesson starts.

Acceptance checklist

Open-ended self-check

1. Using this lesson's 13-stage pipeline, walk through the full processing of ll ~/bashlab/data/*.csv > "$out" 2>&1 's processing steps.

Read input → tokenize (ll,~/bashlab/data/*.csv,>,"$out",2>&1) → alias ll replaced with ls -l → syntax analysis (simple command + two redirections) → brace expansion (none) → tilde expansion to /home/labadmin/…,"$out" expansion → word splitting (no unquoted expansion results) → pathname *.csv → servers.csv → quote removal → lookup ls (not a function / builtin → hash or PATH → /usr/bin/ls) → fork → in the child process, in order, open + dup2 set up fd 1 and fd 2 → execve → wait → $?.

2. Why must cd,export,read be builtin commands? Give one example of “what would happen if it were an external command”.

They modify the shell process's own state (working directory, environment, variables). If cd were an external program, it would run in a forked child process chdir and exit, leaving the parent shell's directory unchanged, just like ( cd /tmp ) does nothing.

3. Give three different symptoms caused by “a missing pair of double quotes”, and explain which expansion stage each occurs in.

① a filename containing spaces is split into two arguments (word splitting); ② a value of * or containing [ is replaced by a list of files (pathname expansion); ③ an empty value disappears, causing [ $x = y ] to report “unary operator expected” (an unquoted empty expansion is removed). Also: multiple consecutive spaces get collapsed (after splitting, echo rejoins them with single spaces).

4. cmd 2>&1 > f and cmd > f 2>&1 differ? How do you send only stderr into a pipe?

Redirections run left to right,2>&1 copies fd 1 as it pointed at that moment. The former leaves errors on the terminal and only output goes to the file; the latter sends both into the file. To send only stderr: cmd 2>&1 >/dev/null | grep ….

5. Write a pipeline that “fails silently”, and give at least two ways to make the failure visible.

pg_dump app | gzip > app.sql.gz: when pg_dump fails, the pipeline status is still gzip's 0. Methods: set -o pipefail; check "${PIPESTATUS[@]}"; or split into two steps, write to a temp file, and check each step; then add output validation (gzip -t, size thresholds).

6. How do subshells and “new Bash processes” differ in variable inheritance? Give one example of syntax that creates each.

A subshell is created by fork and inherits all variables, functions, and options (( … ),$( … ) pipeline segments,&); a new Bash process is started by execve and inherits only environment variables (bash -c,./script.sh). Neither can modify the parent process.

Source and version notes

All version facts were verified on 2026-11-17 against ftp.gnu.org, the Bash NEWS (tiswww.case.edu), bash(1) (man7.org), Docker Hub and YouTube oEmbed
Verification date 2026-11-17
TopicVerified resultSources (accessed 2026-11-17)
Current Bash versionbash-5.3.tar.gz was released on 2025-07-30 (preceded by 5.3-rc2 2025-06, 5.3-rc1 2025-04 and 5.3-beta 2024-12); the latest patch in the official bash-5.3-patches directory is bash53-020 (2026-09-14), i.e. 5.3.20; the final 5.2 series release is 5.2.37 (2024-09)ftp.gnu.org/gnu/bash;bash-5.3-patches
New features in Bash 5.3Command substitution without fork ${ command; } and using REPLY as the result of ${|command;}; GLOBSORT (glob results sorted by name/size/blocks/mtime/atime/ctime/numeric/none); BASH_TRAPSIG; source -p PATH; read -E; compgen -V; array_expand_once replaces assoc_expand_once; bash_source_fullpath; in POSIX mode test the < > locale-based comparison, etc.Bash NEWS
expansion order“brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; pathname expansion; and quote removal”; process substitution is an additional expansion on systems that support it; quote removal always runs lastbash(1) EXPANSION;Bash Manual: Shell Expansions
AliasesIn non-interactive shells, aliases are not expanded unless shopt -s expand_aliases they are enabled; otherwise only unquoted words that can be the first word of a simple command are checked; when an alias value ends in a blank, the next word is checked too.bash(1) ALIASES
Startup filesInteractive login shells: /etc/profile, then ~/.bash_profile,~/.bash_login,~/.profile the first one that exists; interactive non-login shells: ~/.bashrc non-interactive shells: BASH_ENV. This lesson was verified on Bash 5.2 using a sandboxed HOME.Bash Startup Files; bash(1) INVOCATION
Command lookup and exit codesfunction → builtin → hash table → PATH; when not found command_not_found_handle / 127; not executable 126; signal 128+NCommand Search and Execution;Exit Status
shebangis parsed by the kernel at execve time; at most one optional argument after the interpreterexecve(2)
Container imageOfficial Docker image bash tags exist 5.3,5.3.20,5.3-alpine3.24,5.3.20-alpine3.24, and 3.2.57 other historical versions, and devel; the image is based on AlpineDocker Hub: bash tags
Ubuntu 26.04 / macOSUbuntu 26.04 LTS ships bash 5.3 and the default rust-coreutils (consistent with the verification in Linux course Lesson 1); macOS's /bin/bash is 3.2.57Linux Lesson 1 source page(packages.ubuntu.com resolute/bash)
Sample datasetmake-data.sh was run twice on Bash 5.2.37 and the output is byte-identical; cksum: access.log 80306651 79109, servers.csv 3087317886 526, inventory.json 3924293688 1199, config.yaml 1138550665 787Actual run for this lesson (scratchpad)

Video verification notes

This lesson lists only videos whose titles and channels were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17:

oEmbed only verified titles and channels; the videos were not watched segment by segment. Content descriptions in “meta” come from titles and public information and may differ from the actual video details. Most of these videos are based on Bash 5.2 or earlier; for the Bash 5.3 new features, this lesson is authoritative. No verified video was found that specifically covers the “seven-step expansion order”, “fd duplication order”, “PIPESTATUS / pipefail” or “subshell and environment inheritance”; for those topics, refer to this lesson's animations and storyboard script.

Voice narration notes

The “Voice” tab uses the browser's built-in Web Speech API to read the Chinese narration script (zh-CN) and the English terms (en-US); it needs no network access or external scripts. This courseware cannot embed MP3 files or generate video; the narration script and storyboard can be passed to a TTS or video tool to produce audio and video.

Known limitations

  • Actual run environment: output labeled “actual run result (Bash 5.2)” was obtained by running it in Git Bash on Windows (GNU bash 5.2.37, MSYS2); paths have been replaced with /home/labadmin/…. Differences between Git Bash and Linux: there are no true fork semantics or permission bits; CRLF is tolerated (so CRLF-related output is marked “example”); wc / grep are the GNU versions bundled with Git for Windows. Not actually run on Bash 5.3 or Ubuntu 26.04: ${ cmd; } / ${| cmd; } output was written based on the Bash NEWS and the manual, and is labeled “expected output”.
  • Content labeled “expected output / example” was not actually run; the PIDs, timestamps and patch levels in it (such as 5.3.3), strace system calls,time timings are illustrative; the error wording of Ubuntu 26.04's rust-coreutils (uutils) and GNU tools,ls sort order may differ.
  • Sort-related output (glob results,ls,sort) depends on the locale and the Bash 5.3 GLOBSORT setting; when a reproducible order is needed, use LC_ALL=C.
  • The “parsing and execution pipeline”, “command lookup”, “fd table”, “pipes”, “environment inheritance”, “script execution” and other animations are based on the stage breakdown in the Bash manual and on the public function names in the Bash source (parse.y,subst.c,execute_cmd.c,redir.c) and simplified; the implementation omits the vfork optimization, signal handling, job control, and the subshell optimization that runs the last command directly with exec; the tokenizer animation implements only quoting $VAR/${VAR}, word splitting, and */? globbing.
  • A non-interactive Bash started by sshd reads ~/.bashrc, and Debian/Ubuntu's /etc/bash.bashrc depends on build options (SSH_SOURCE_BASHRC,SYS_BASHRC); it may differ between distributions, so actual testing is authoritative.
  • Ubuntu 26.04's default sudo-rs, when preserving environment variables (env_reset,--preserve-env) behavior has not been tested on 26.04; use the sudo env output as the reference.
  • Official Docker bash image tags follow Docker Hub as verified on that day; the image is based on Alpine, and its coreutils are a BusyBox implementation.