Globbing and Wildcards
In this page:
Matching Any Characters with *
The asterisk matches any sequence of characters, including none. Bash expands *.txt into a list of every matching filename in the current directory before the command runs.
Example: Matching Any Characters with *
#!/bin/bash
touch a.txt b.txt c.log
echo *.txt
rm -f a.txt b.txt c.log
Login to try C/C++/Java/PHP code in the editor
Matching a Single Character with ?
The question mark matches exactly one arbitrary character, no more and no less, which is useful for fixed-width patterns like file?.txt matching file1.txt but not file10.txt.
Example: Matching a Single Character with ?
#!/bin/bash
touch file1.txt file2.txt file10.txt
echo file?.txt
rm -f file1.txt file2.txt file10.txt
Login to try C/C++/Java/PHP code in the editor
Character Classes with [...]
Square brackets match any single character from the set (or range) listed inside them, such as [abc] or [0-9], giving more precise control than * or ?.
Example: Character Classes with [...]
#!/bin/bash
touch report1.txt report2.txt reportX.txt
echo report[0-9].txt
rm -f report1.txt report2.txt reportX.txt
Login to try C/C++/Java/PHP code in the editor
Handling No Matches Safely
If a glob pattern matches nothing, Bash leaves the pattern text unexpanded by default, which can confuse scripts expecting a real filename. Enabling nullglob makes an unmatched pattern expand to nothing instead.
Note: Set shopt -s nullglob at the top of scripts that loop over glob results, so empty matches don't produce one bogus iteration.
Example: Handling No Matches Safely
#!/bin/bash
shopt -s nullglob
matches=(*.nonexistent)
echo "Number of matches: ${#matches[@]}"
shopt -u nullglob
Login to try C/C++/Java/PHP code in the editor
- Believing
*and?are regular expressions; they are glob patterns with different rules (*matches any string,.is literal, not "any character"). - Forgetting that an unmatched glob pattern is left as a literal string by default, which can silently break a script (
nullglobor explicit checks fix this). - Not quoting glob results after expansion when passing them onward, causing filenames with spaces to split incorrectly.
*matches zero or more of any character;?matches exactly one character;[...]matches any one character in the set.- Glob expansion happens before the command even runs, done entirely by Bash itself.
shopt -s nullglobmakes an unmatched pattern expand to nothing instead of the literal pattern text.- Glob patterns are not regular expressions, despite looking similar.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: