← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 4 of 13

Globbing and Wildcards

Globbing lets you use symbols like * and ? in a filename pattern so Bash automatically expands them to match real files.

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 *

bash
#!/bin/bash
touch a.txt b.txt c.log
echo *.txt
rm -f a.txt b.txt c.log

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 ?

bash
#!/bin/bash
touch file1.txt file2.txt file10.txt
echo file?.txt
rm -f file1.txt file2.txt file10.txt

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 [...]

bash
#!/bin/bash
touch report1.txt report2.txt reportX.txt
echo report[0-9].txt
rm -f report1.txt report2.txt reportX.txt

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

bash
#!/bin/bash
shopt -s nullglob
matches=(*.nonexistent)
echo "Number of matches: ${#matches[@]}"
shopt -u nullglob
Common Mistakes
  1. Believing * and ? are regular expressions; they are glob patterns with different rules (* matches any string, . is literal, not "any character").
  2. Forgetting that an unmatched glob pattern is left as a literal string by default, which can silently break a script (nullglob or explicit checks fix this).
  3. Not quoting glob results after expansion when passing them onward, causing filenames with spaces to split incorrectly.
Chapter Summary
  • * 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 nullglob makes an unmatched pattern expand to nothing instead of the literal pattern text.
  • Glob patterns are not regular expressions, despite looking similar.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.