Lesson 2 of 14 · 22m
Expansion and Globbing: The Line Before the Command
The shell rewrites every line before running it — brace, parameter, command, word-split, then glob — and most file-deletion bugs are expansion doing exactly what you wrote.
Before the shell runs anything, it rewrites the line you typed. rm *.txt never reaches rm as the string *.txt — the shell expands the glob against the directory listing and hands rm an argv of real filenames. rm cannot delete a file literally named *.txt unless you quote it, because * is shell syntax, not rm syntax. Most "the command ate my files" bugs are really "the expansion did what you wrote, not what you meant."
The expansion order
Bash applies expansions in a fixed order (it's in the man page under EXPANSION): brace expansion, tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, word splitting, then pathname expansion. Two consequences matter daily:
- Word splitting happens after
$varexpands.file="my doc.txt"; rm $filerunsrm my doc.txt— two arguments.rm "$file"is one. Quote every expansion; unquoted$varis a request for word splitting and globbing on the result. - Globbing is last, so
var="*.txt"; rm $vardoes expand the*. Storing a pattern in a variable does not quote it.
Brace expansion is pure text: cp file{,.bak}, touch report_{2024..2026}.md, mkdir -p app/{src,tests,docs}. It runs before anything touches the filesystem — nothing has to exist.
Parameter expansion is a language
The ${var...} forms replace whole subprocesses:
name="${path##*/}" # basename — strip longest leading */ match
dir="${path%/*}" # dirname — strip shortest trailing /* match
ext="${name##*.}" # extension after the last dot
stem="${name%.*}" # filename minus extension
len="${#var}" # string length
def="${var:-fallback}" # var if set-and-nonempty, else fallback
need="${var:?var must be set}" # abort with message if unset/empty
first5="${var:0:5}" # substring
upper="${var^^}" # uppercase (bash 4+)${var:?} is the cheapest defensive check a script can carry — rm -rf "${BUILD_DIR:?}/"* aborts on an empty path instead of globbing into rm -rf /*. This is not hypothetical: in January 2015 the Steam installer for Linux shipped exactly that line — rm -rf "$STEAMROOT/"*, with STEAMROOT able to come out empty — and the unquoted glob expanded to /*. GNU rm's --preserve-root refuses a literal /, but it never saw one; it saw a list of root's children. One parameter expansion is the difference between that incident and a clean exit.
Command and process substitution
$(cmd) captures stdout — and strips all trailing newlines. $(< file) is the same capture without spawning cat — bash reads the file itself. Backticks are the legacy form: no nesting, quoting ambiguities, nothing to recommend them.
<(cmd) produces a path (/dev/fd/63-style FIFO) to the command's output — the bridge when a tool insists on a file and your data is a stream:
diff <(sort a.txt) <(sort b.txt)Globbing rules
*and?never match a leading dot —rm *spares dotfiles, which is the point..*matches.and...chmod -R 700 .*recurses into your parent directory. Classic footgun, still shipping.- An unmatched glob passes through literally:
for f in *.txtin an empty directory iterates once withf="*.txt".shopt -s nullglobmakes the glob vanish instead;failglobmakes it an error. shopt -s globstarenables**recursion;shopt -s extglobenables*(a|b),!(pattern)patterns.[[ $name == *.txt ]]— inside[[ ]], no word splitting or globbing applies to the left side, and==is a pattern match.[is a regular command (/usr/bin/[exists), splits and globs normally, and its equality operator is=.[[ ]]is the safe context; that's why scripts should use it.
Practice
"$var", always;"$@"for argv;"${arr[@]}"for arrays.${var:?}before any destructive path.[[ ... ]]for conditions;[only when POSIX forces it.nullglobin scripts that loop over patterns that might match nothing.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Red Hat Called This Bug a 5.9. Two Weeks Later It Was a 9.8.
CVE-2026-98432 is a use-after-free in the IPv4 TCP handshake, reachable by anybody who can reach a listening port, sitting in the kernel since 4.4. Red Hat scored it 5.9 moderate and deferred the fix. Then 8.1. Then 9.8.
Self-Host OpenClaw: VPS Setup to Production (2026)
Self-host OpenClaw from zero to production. Server provisioning, SSH lockdown, Docker, reverse proxy, Fail2ban, performance tuning, and full backup strategy in one guide.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.