Skip to content

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 $var expands. file="my doc.txt"; rm $file runs rm my doc.txt — two arguments. rm "$file" is one. Quote every expansion; unquoted $var is a request for word splitting and globbing on the result.
  • Globbing is last, so var="*.txt"; rm $var does 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 *.txt in an empty directory iterates once with f="*.txt". shopt -s nullglob makes the glob vanish instead; failglob makes it an error.
  • shopt -s globstar enables ** recursion; shopt -s extglob enables *(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.
  • nullglob in scripts that loop over patterns that might match nothing.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.