Filename Expansion and Globbing
Filename expansion, also called globbing or pathname expansion, is how Bash turns a pattern such as *.txt into the list of files that match it. You type the pattern; Bash searches the directory, builds the list of matching names, and hands that list to the command. The command itself never sees the pattern.
Understanding the Concept
Many commands need to work on groups of files: all text files, every report from last month, every image in a folder. Typing each name would be slow, so the shell lets you describe a group with a pattern. A pattern is made of ordinary characters, which match themselves, and special characters, which match many possibilities.
The key idea is that the shell does the matching, not the command. When you run ls *.txt, Bash expands *.txt first, and ls receives a plain list of names. The echo command is a good way to see what the shell produces, because it prints its arguments exactly as it received them.
The examples in this lesson use a folder created like this:
mkdir -p globdemo/docs globdemo/empty
cd globdemo
touch a.txt b.txt c.md notes.txt "my file.txt" A.TXT
touch report1.csv report2.csv report10.csv file.tar.gz .hidden
touch docs/x.txt docs/y.md
How Bash Expands a Pattern
Bash checks every word of a command after it has finished the earlier expansions. A word that contains an unquoted *, ? or [ is treated as a pattern. Bash then:
- Reads the names in the directory the pattern refers to.
- Keeps the names that match the whole pattern.
- Sorts the matches.
- Replaces the pattern with the sorted names, one word per name.
If no name matches, Bash leaves the pattern as it was (this default can be changed, as described later).
echo *.txt
Output:
a.txt b.txt my file.txt notes.txt
echo received four arguments. The file A.TXT was not included, because matching is case-sensitive.
Pattern Characters
| Pattern | Matches |
|---|---|
* | Any sequence of characters, including none |
? | Exactly one character |
[abc] | One character from the list |
[a-c] | One character in the range |
[!abc] or [^abc] | One character that is not in the list |
[[:class:]] | One character from a named class |
The Asterisk and the Question Mark
echo *
echo report?.csv
echo report??.csv
Output:
A.TXT a.txt b.txt c.md docs empty file.tar.gz my file.txt notes.txt report1.csv report10.csv report2.csv
report1.csv report2.csv
report10.csv
*alone matched every visible name in the folder, including the foldersdocsandempty.report?.csvneeds exactly one character betweenreportand.csv, soreport10.csv, which has two, did not match.report??.csvneeds exactly two characters, so onlyreport10.csvmatched.
Lists and Ranges
echo [ab].txt
echo [a-c].*
echo report[0-9].csv
echo report[!1].csv
echo report[^1].csv
Output:
a.txt b.txt
a.txt b.txt c.md
report1.csv report2.csv
report2.csv
report2.csv
Square brackets match one character. [ab] accepts a or b. [a-c] accepts any character from a to c. A ! (or ^) at the start reverses the list, so report[!1].csv means "report, then any one character except 1, then .csv". The ! form is the standard one; [^...] works in Bash but not in every shell.
Character Classes
Named classes avoid depending on alphabets and ranges. They are written inside the brackets, so you see two pairs:
echo [[:upper:]].TXT
echo report[[:digit:]].csv
echo [[:digit:]]*
Output:
A.TXT
report1.csv report2.csv
[[:digit:]]*
The common classes are [:alpha:], [:digit:], [:alnum:], [:upper:], [:lower:] and [:space:]. The last command shows what happens when nothing matches: no file name starts with a digit, so the pattern was printed unchanged.
Wildcards and Directories
A wildcard never matches the slash that separates directory names. A pattern must spell out each directory level, although each level can use wildcards of its own:
echo docs/*
echo */
echo */*.txt
Output:
docs/x.txt docs/y.md
docs/ empty/
docs/x.txt
docs/*matched everything insidedocs.*/matched only directories, because the trailing slash can only belong to a directory.*/*.txtlooked inside every directory for.txtfiles and found onlydocs/x.txt. Thea.txtandb.txtfiles in the current folder are not found, since the pattern requires one directory level.
Hidden Files
Names that start with a dot are hidden. A pattern does not match a leading dot unless the pattern itself starts with a dot:
echo .h*
echo .*
Output:
.hidden
.hidden
Plain * never produced .hidden. In Bash 5.2 and later, a pattern such as .* also skips the special entries . and .. (the globskipdots option, which is on by default), so only .hidden matched. Older versions of Bash include . and .. in this list, which can cause surprises with commands such as rm.
Sorting and Locale
Bash sorts the matches according to the current locale. In the default C locale, used for the examples here, capital letters sort before lowercase letters, and names are compared character by character:
echo report*.csv
Output:
report1.csv report10.csv report2.csv
The comparison is alphabetical, not numeric, so report10.csv appears before report2.csv. In other locales, the relative order of upper and lower case names can differ, so a script should not depend on it. Zero-padded names such as report01.csv and report02.csv keep a natural order.
Spaces and Special Characters in Matched Names
Each matched name becomes exactly one word, even if it contains spaces. Bash does not split the results again:
printf '[%s]\n' my*
Output:
[my file.txt]
echo hides this, since it joins its arguments with spaces. printf with a [%s] format shows the true word boundaries. This is why a loop such as for f in *.txt is safe with unusual names, while building a list of names as text and splitting it later is not.
When Nothing Matches
If no file matches, the pattern stays in the command as ordinary text:
echo *.xyz
ls *.xyz
Output:
*.xyz
ls: cannot access '*.xyz': No such file or directory
echo printed the pattern because there was nothing to replace it with. ls tried to open a file literally named *.xyz and failed, with exit status 2. Scripts that loop over *.log need to cope with this case, because the loop body would run once with the text *.log as the "file name". Shell options, described below, offer better behavior.
Quoting Turns Globbing Off
Quotes and backslashes make the special characters ordinary:
echo "*.txt"
echo '*.txt'
echo \*.txt
Output:
*.txt
*.txt
*.txt
This is how you pass a pattern to a command that does its own matching, such as find -name "*.txt", instead of letting the shell expand it first.
Globs in Variables
A pattern stored in a variable stays a pattern. Whether it is expanded depends on quotes at the moment of use:
pat='*.md'
echo $pat
echo "$pat"
Output:
c.md
*.md
The unquoted $pat is expanded to its value and then treated as a pattern, so it matched c.md. The quoted version keeps the text unchanged. Later lessons on word splitting and quoting variables explain this behavior in detail.
Using Globs in Loops and Arrays
A for loop receives each match as one item:
for f in *.csv; do echo "file: $f"; done
Output:
file: report1.csv
file: report10.csv
file: report2.csv
A pattern can also fill an array, which lets you count the matches:
files=(*.txt)
echo "${#files[@]} files: ${files[*]}"
Output:
4 files: a.txt b.txt my file.txt notes.txt
Shell Options That Change Globbing
Several shopt options change how patterns behave. Turn an option on with shopt -s name and off with shopt -u name.
| Option | Effect |
|---|---|
nullglob | A pattern with no matches expands to nothing |
failglob | A pattern with no matches is an error, and the command does not run |
dotglob | Patterns also match names that start with a dot |
nocaseglob | Matching ignores letter case |
globstar | ** matches files and directories recursively |
nullglob
shopt -s nullglob
echo *.xyz
set -- *.xyz
echo "count=$#"
shopt -u nullglob
Output (the first line is empty):
count=0
The pattern vanished, which is exactly what a loop over possibly-missing files needs: with nullglob, for f in *.log runs zero times when there are no logs.
failglob
shopt -s failglob
echo *.xyz
echo "status=$?"
shopt -u failglob
Output:
bash: no match: *.xyz
status=1
The command echo never ran. In a script, the message also names the script and line number.
dotglob
shopt -s dotglob
echo *
shopt -u dotglob
Output:
.hidden A.TXT a.txt b.txt c.md docs empty file.tar.gz my file.txt notes.txt report1.csv report10.csv report2.csv
nocaseglob
shopt -s nocaseglob
echo *.txt
shopt -u nocaseglob
Output:
A.TXT a.txt b.txt my file.txt notes.txt
Now A.TXT matched too.
globstar
shopt -s globstar
echo **/*.txt
shopt -u globstar
Output:
a.txt b.txt docs/x.txt my file.txt notes.txt
With globstar, **/ stands for "any number of directories, including none", so the pattern found the files in the current folder and in docs.
GLOBIGNORE and set -f
The variable GLOBIGNORE holds a colon-separated list of patterns that are removed from the results:
GLOBIGNORE='b.txt'
echo *.txt
Output:
a.txt my file.txt notes.txt
Setting GLOBIGNORE has a side effect: it also turns on dotglob behavior, and clearing the variable afterwards did not turn it off again in Bash 5.2.21. Set it inside a subshell, written as ( GLOBIGNORE=...; commands ), so the effect does not leak into the rest of the script.
Finally, set -f turns filename expansion off completely, and set +f turns it back on:
set -f
echo *.txt
set +f
echo *.txt
Output:
*.txt
a.txt b.txt my file.txt notes.txt
Globs Are Not Regular Expressions
Glob patterns look similar to regular expressions but follow different rules. Do not mix them up:
| Meaning | Glob | Regular expression |
|---|---|---|
| Any text | * | .* |
| Any one character | ? | . |
| Files ending in .txt | *.txt | .* 0 txt$ |
A glob is matched against the entire name, so *.txt must end with .txt. Commands such as grep use regular expressions, which is why grep "*.txt" file does not mean "files ending in .txt".
Previewing a Glob Before Using It
Because patterns can match more than you expect, it is wise to look at the expansion before running a command that changes or deletes files. Replace the command with echo, check the result, and then run the real command:
echo report*.csv
Output:
report1.csv report10.csv report2.csv
If the list is what you intended, repeat the line with the real command in place of echo.
Availability in Other Shells
The characters *, ? and [...] work in every POSIX shell. Dash, for example, expands *.txt and [!a]*.txt the same way as Bash. The negation written with a caret, [^a], is a Bash habit: in Dash the caret is an ordinary character, so [^a].txt matched a.txt there. Use [!a] in scripts that must run under sh. The options nullglob, failglob, dotglob, nocaseglob and globstar are Bash features, and extended patterns are covered in a later lesson on pattern matching.