Wildcards & Globbing
The shell expands wildcards like * and ? into matching file names before a command runs.
Before running a command, the shell replaces wildcards with the list of file names they match. This is called globbing.
The wildcards
| Pattern | Matches |
|---|---|
* | Any number of characters (including none). |
? | Exactly one character. |
[abc] | Any one of a, b or c. |
[0-9] | Any single digit. |
{jpg,png} | Either literal word (brace expansion). |
For example, *.txt matches every file ending in .txt, and report?.txt matches report1.txt but not report10.txt.
Example
# All text files
ls *.txt
# Files named img1 to img9
ls img?.jpg
# Files starting with a, b or c
ls [abc]*
# Copy both jpg and png files at once (brace expansion)
cp *.{jpg,png} images/When to use it
- A developer deletes all compiled object files with 'rm *.o' using a wildcard to avoid listing each file manually.
- A sysadmin copies only YAML config files with 'cp /deploy/*.yaml /etc/app/' to target a specific file type.
- A log-rotation script uses 'gzip access.log.[0-9]' to compress only numbered log files, leaving the current log untouched.
More examples
Glob with star and question mark
Demonstrates the two most common glob characters: * for any-length matches and ? for single-character matches.
# * matches any sequence of characters
ls /etc/*.conf
# ? matches exactly one character
ls /dev/sd?
# /dev/sda /dev/sdbCharacter classes in globs
Uses bracket expressions [0-9] and brace expansion {jpg,png} to precisely target file groups.
# Match files starting with a digit
ls /var/log/syslog.[0-9]*
# Match .jpg or .png (not .jpeg)
ls photos/img_[0-9][0-9][0-9].{jpg,png}Recursive glob with globstar
Enables the globstar option so ** matches across multiple directory levels recursively.
# Enable globstar in bash
shopt -s globstar
# Match all .js files in any subdirectory
ls **/*.js
# Count them
ls **/*.js | wc -l
Discussion