Globbing
Bash · Reference cheat sheet
Globbing
Bash · Reference cheat sheet
📋 Overview
Globs (pathname expansion) match filenames with *, ?, and [] before the command runs. Unlike regex, * never matches / across directories unless globstar is on. Quote patterns when you want literals; enable nullglob / failglob for safer scripts.
🔧 Core concepts
| Pattern | Matches |
|---|---|
* | Any string except / |
? | Single character |
[abc] / [a-z] | Character class |
[!a] / [^a] | Negated class |
** | Recursive (needs shopt -s globstar) |
*(pat) etc. | Extglob patterns (shopt -s extglob) |
shopt | Effect |
|---|---|
nullglob | Unmatched glob → empty |
failglob | Unmatched glob → error |
dotglob | Include .hidden |
nocaseglob | Case-insensitive |
globstar | Enable ** |
💡 Examples
Safe iteration:
shopt -s nullglob
for f in *.log; do
echo "$f"
doneExtglob:
shopt -s extglob
rm -- !(keep|also-keep).tmp
ls *.(jpg|png|gif)Globstar:
shopt -s globstar nullglob
for f in **/*.py; do
echo "$f"
doneDisable expansion:
echo "*.txt" # literal
printf '%s\n' *.txt # expanded list⚠️ Pitfalls
- Default: unmatched
*.txtstays as the literal string*.txt—dangerous inrm. - Globs don’t sort the way you always expect across locales; sort explicitly if needed.
**withoutglobstaris just two*tokens in some contexts—enable the option.- Brace expansion
\{a,b\}is not globbing; it runs even if files don’t exist. - Leading
.files ignored unlessdotglobor pattern starts with.. - Never parse
ls; use globs orfind.