What is File Globbing?
File globbing refers to the use of wildcards to match filenames or paths. It’s handled by the shell (e.g., Bash), not by the command itself.
It allows you to match:
- Multiple files at once
- Files based on patterns
- Files by type or extension
Common Globbing Patterns
Pattern | Meaning | Example | Matches |
---|---|---|---|
* | Matches zero or more characters (except / ) | *.txt | a.txt , file.txt , note1.txt |
? | Matches exactly one character | ?.txt | a.txt , b.txt (but not ab.txt ) |
[] | Matches any one character from the set | [ab].txt | a.txt , b.txt |
[!x] | Matches any one character except x | [!a]* | Files not starting with a |
[a-z] | Matches any single character in a range | [a-c]* | apple , banana , cat |
{} | Matches any one of comma-separated patterns | {.txt,.sh} | Files ending with .txt or .sh |
\ | Escapes the next character (used to match special characters literally) | file\* | Matches a file literally named file* |
Examples
*
– Match Any Number of Characters
ls *.sh
Matches: script.sh
, install.sh
, but not file.txt
.
?
– Match Exactly One Character
ls ?.txt
Matches: a.txt
, b.txt
, but not ab.txt
or abc.txt
.
[]
– Match Specific Characters
ls [ab]*.txt
Matches: a.txt
, bfile.txt
, but not c.txt
.
[^]
– Negate a Character Set
ls [!a]*.txt
Matches: b.txt
, c.txt
, but not a.txt
.
[a-z]
– Match a Character Range
ls file[1-3].txt
Matches: file1.txt
, file2.txt
, file3.txt
.
{}
– Match Multiple Alternatives
ls *.{sh,txt}
Matches: file.sh
, notes.txt
, but not image.png
.
Globbing vs Regular Expressions
Feature | Globbing | Regex |
---|---|---|
Used in | Shell commands (ls, rm, etc.) | grep, sed, awk |
Simpler | ✅ | ❌ |
Powerful Matching | ❌ | ✅ |
Syntax | * , ? , [] | .* , ^ , $ , \d , etc. |
Disable Globbing Temporarily (Optional)
If you want to pass wildcard characters literally:
set -f # Disable globbing
ls *.txt # Will literally look for *.txt
set +f # Re-enable globbing
Summary Table
Pattern | Description | Matches |
---|---|---|
* | Zero or more characters | file.txt , hello.sh |
? | Exactly one character | a.txt , b.txt |
[abc] | One character in list | a.txt , b.txt |
[a-z] | Character in range | filea , fileb , …, filez |
[!x] | Not the character x | Anything except files starting with x |
{a,b} | Either pattern a or b | *.txt , *.sh |
\* | Escaped * (literal asterisk) | File named * |
Last updated on