Terminal · foundation

Filename expansion (globbing)

Filename expansion is the shell step that replaces unquoted pathname patterns such as *, ?, and bracket expressions with matching existing pathnames before launching a command.

Why it matters

The shell, not the target program, usually expands globs, so quoting and the current directory can radically change the arguments a command receives.

Mental model

How to reason about filename expansion (globbing)

Before execution, the shell searches the relevant directory for names matching each unquoted pattern and substitutes a sorted implementation-dependent list of pathnames according to shell settings.

Analogy

A glob is a request to the shell's filing clerk: the clerk replaces the pattern card with every matching filename before handing the stack to the program.

Examples

See the boundary, not just the happy path

Worked example · Select log files

printf '%s\n' logs/*.log

The shell expands the pattern to matching names in logs, and printf receives one argument per matched pathname.

Worked example · Match one varying character

ls -- report-?.csv

The ? matches exactly one pathname character, so report-1.csv matches but report-10.csv does not.

Useful contrast · Quoted pattern

printf '%s\n' '*.log'

Quoting prevents filename expansion, so printf receives the literal pattern rather than matching paths.

Common mistakes

Misconceptions to remove early

Calling globs regular expressions

They are distinct pattern languages: glob * means any string, while regex * repeats the preceding expression.

Assuming unmatched patterns always disappear

Default behavior varies by shell and options; Bash normally leaves an unmatched pattern literal, while nullglob can remove it and failglob can reject it.

Quick check

Can you predict the result?

1. Who normally expands *.txt in the command wc -l *.txt?
  • The shell
  • wc
  • The filesystem driver after wc starts
Answer: The shell
2. Why does '*.txt' not select files?
Answer: The quotes suppress filename expansion, leaving the pattern literal.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster