Code Reference

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

PatternMatches
*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)
shoptEffect
nullglobUnmatched glob → empty
failglobUnmatched glob → error
dotglobInclude .hidden
nocaseglobCase-insensitive
globstarEnable **

💡 Examples

Safe iteration:

shopt -s nullglob
for f in *.log; do
  echo "$f"
done

Extglob:

shopt -s extglob
rm -- !(keep|also-keep).tmp
ls *.(jpg|png|gif)

Globstar:

shopt -s globstar nullglob
for f in **/*.py; do
  echo "$f"
done

Disable expansion:

echo "*.txt"           # literal
printf '%s\n' *.txt    # expanded list

⚠️ Pitfalls

  • Default: unmatched *.txt stays as the literal string *.txt—dangerous in rm.
  • Globs don’t sort the way you always expect across locales; sort explicitly if needed.
  • ** without globstar is 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 unless dotglob or pattern starts with ..
  • Never parse ls; use globs or find.

On this page