Skip to content
AgileLogics
4 min read

Wildcards and Globbing

Prerequisites: Working with files and directories

Wildcards match file names by pattern. Bash expands them into the list of matching names before the command runs — this is called globbing.

touch report-jan.csv report-feb.csv report-mar.csv notes.txt photo1.jpg photo2.jpg photo10.jpg

echo *.csv
echo report-???.csv
echo photo?.jpg
echo photo[12].jpg
echo *.{jpg,txt}
report-feb.csv report-jan.csv report-mar.csv
report-feb.csv report-jan.csv report-mar.csv
photo1.jpg photo2.jpg
photo1.jpg photo2.jpg
photo1.jpg photo10.jpg photo2.jpg notes.txt
Pattern Matches
* any number of characters (including none)
? exactly one character
[abc] one of the listed characters
[0-9] one character in a range

{jpg,txt} is brace expansion — it isn't a pattern match; Bash simply writes out each alternative (*.jpg *.txt). It also generates sequences:

echo file{1..3}.txt
echo {a..e}
file1.txt file2.txt file3.txt
a b c d e

Wildcards in real commands

touch a.log b.log keep.txt
mkdir old-logs
mv *.log old-logs/
ls
ls old-logs
keep.txt
old-logs
a.log
b.log

When nothing matches

If a pattern matches nothing, Bash leaves it as-is:

echo *.pdf
*.pdf

That can surprise scripts (a loop runs once with the literal *.pdf). shopt -s nullglob makes unmatched patterns expand to nothing instead — covered in Level 3.

Common mistakes

  • rm * .txt (with a space) means "delete everything, then .txt" — not "delete .txt files". Always check with echo or ls before deleting by pattern.
  • Hidden files (starting with .) aren't matched by *.