Pattern Matching and Extended Globbing
Bash has its own small pattern language, the glob pattern, which it uses in more places than most people realise. Lesson 52 showed globs expanding into file names, such as *.txt. The same patterns decide which branch of a case statement runs (lesson 76), what [[ $x == pattern ]] tests (lesson 69), and what ${var#pattern} removes (lesson 152). Learning the language once therefore improves file selection, input validation and string editing together.
This lesson covers the full pattern syntax, the extended globbing operators that add "one of", "one or more" and "anything except", the recursive ** pattern, and the shell options that change how matching behaves.
Where Bash Uses Patterns
| Context | Example | What the pattern is matched against |
|---|---|---|
| Filename expansion | ls *.log | names of files on disk |
[[ ]] with == or != | [[ $file == *.log ]] | a string |
case | case $file in *.log) ... | a string |
| Parameter expansion | ${file%.log} | a variable's value |
The pattern language is the same in all four. The difference is what happens with the result: filename expansion produces a list of file names, while the other three produce a yes/no answer or an edited string and never look at the disk.
The Basic Pattern Syntax
| Pattern | Matches |
|---|---|
* | any text, including nothing |
? | exactly one character |
[abc] | one character from the set |
[a-z] | one character in the range |
[!abc] or [^abc] | one character not in the set |
[[:class:]] | one character from a named class |
The named character classes are the most reliable way to describe groups of characters:
| Class | Characters |
|---|---|
[:digit:] | 0–9 |
[:alpha:] | letters |
[:alnum:] | letters and digits |
[:upper:] / [:lower:] | upper- / lower-case letters |
[:space:] | space, tab, newline and other white space |
[:punct:] | punctuation characters |
Note the double brackets: [[:digit:]] is a bracket expression [...] that contains the class [:digit:]. You can combine classes and characters, such as [[:alnum:]_-].
Ranges like [a-z] once depended on the locale (the language settings), so in some locales [a-z] also matched upper-case letters. Since Bash 5.0, the option globasciiranges is on by default and ranges use plain ASCII order. Classes avoid the question entirely, which is why they are preferred in scripts that may run on many systems.
Basic Examples
The examples in this lesson run in a folder containing these files:
app.js app.min.js app.test.js style.css README.md notes.txt .env
photo.JPG photo2.jpeg backup.tar.gz report-2026.pdf report-final.pdf
src/main.js src/lib/util.js src/lib/util.test.js docs/guide.md
echo *.js
echo report-[[:digit:]]*.pdf
echo [[:upper:]]*
app.js app.min.js app.test.js
README.md
report-2026.pdf
The second pattern requires a digit right after report-, so report-final.pdf is excluded. The third matches names that begin with an upper-case letter.
Extended Globbing
The basic syntax cannot say "either .jpg or .png", "one or more digits" or "every file except .js files". Extended globbing adds five operators that can, each of which applies to a pattern list: one or more patterns separated by |.
| Operator | Matches |
|---|---|
?(list) | zero or one occurrence of the patterns |
*(list) | zero or more occurrences |
+(list) | one or more occurrences |
@(list) | exactly one of the patterns |
!(list) | anything except one of the patterns |
These operators resemble regular expressions (?, *, +, |), but the operator comes before the parentheses.
Turning Extended Globbing On
For filename expansion, case and parameter expansion, extended globbing must be enabled with shopt -s extglob (lesson 149). Without it, the parentheses are a syntax error:
$ echo !(*.js)
bash: syntax error near unexpected token `('
Inside [[ ... == ... ]], Bash recognises the extended operators even when extglob is off, which is a convenient exception:
shopt extglob
[[ 123 == +([0-9]) ]] && echo "[[ ]] works without extglob"
extglob off
[[ ]] works without extglob
One rule needs special care. Bash checks the syntax of a line, and of a whole function, when it reads it, before running anything. If shopt -s extglob is inside the same function as the pattern, the option is not yet on when the function is parsed:
check() {
shopt -s extglob
case $1 in +([0-9])) echo "number";; esac
}
t153c.sh: line 3: syntax error near unexpected token `('
The reliable rule is to put shopt -s extglob near the top of the script, on its own line, before any code that uses the operators.
Extended Patterns in Filename Expansion
With shopt -s extglob enabled:
echo *.@(js|css)
echo !(*.js)
echo !(*.min).js
echo !(*.@(min|test)).js
echo photo?(2).*
app.js app.min.js app.test.js style.css
README.md backup.tar.gz docs notes.txt photo.JPG photo2.jpeg report-2026.pdf report-final.pdf src style.css
app.js app.test.js
app.js
photo.JPG photo2.jpeg
Understanding the Examples
*.@(js|css): any name, a dot, then exactly one ofjsorcss.!(*.js): every name that does not end in.js. The result includes the foldersdocsandsrc, because filename expansion matches every kind of entry, not just files. Hidden files such as.envare still excluded, as with any pattern.!(*.min).js: the part before.jsmust not itself end in.min, soapp.min.jsis excluded.!(*.@(min|test)).js: operators can be nested; this excludes both minified and test files.photo?(2).*:photo, an optional2, a dot, then anything.
!(...) is the operator that makes extended globbing so useful in daily work. A command such as rm -- !(*.keep) deletes everything except the files you want to keep, so always preview with echo or ls first (lesson 160).
Extended Patterns for Validation
In [[ ]] and case, extended patterns are a lightweight way to validate input without regular expressions:
for s in 1 12 123 12a ""; do
if [[ $s == +([0-9]) ]]; then echo "$s: number"; else echo "$s: not"; fi
done
1: number
12: number
123: number
12a: not
: not
+([0-9]) means "one or more digits and nothing else". A pattern in [[ ]] must match the whole string, so 12a fails. The empty string also fails, because + requires at least one digit. With *([0-9]), the empty string would pass.
*(list) matches repetitions of a whole pattern, not just of single characters:
for s in ab abab "" aba; do
if [[ $s == *(ab) ]]; then echo "[$s] yes"; else echo "[$s] no"; fi
done
[ab] yes
[abab] yes
[] yes
[aba] no
Patterns can be combined into fairly precise checks, such as a version number in the form MAJOR.MINOR.PATCH with an optional suffix:
for v in 1.2.3 1.2 1.2.3-rc1 v1.2.3 1..2; do
if [[ $v == +([0-9]).+([0-9]).+([0-9])?(-+([[:alnum:]])) ]]; then
echo "$v ok"
else
echo "$v bad"
fi
done
1.2.3 ok
1.2 bad
1.2.3-rc1 ok
v1.2.3 bad
1..2 bad
Read the pattern from left to right: digits, a dot, digits, a dot, digits, and optionally (?(...)) a dash followed by one or more letters or digits.
Extended Patterns in case
case patterns become much more expressive with extended globbing. Combined with nocasematch (described below), one branch can recognise every common image type regardless of letter case:
shopt -s extglob nocasematch
for f in a.jpg b.PNG c.txt; do
case $f in
*.@(jpg|jpeg|png|gif)) echo "$f image" ;;
*) echo "$f other" ;;
esac
done
a.jpg image
b.PNG image
c.txt other
Extended Patterns in Parameter Expansion
The removal and replacement operators from lesson 152 accept extended patterns too, which simplifies tasks such as trimming white space or squeezing repeated characters:
shopt -s extglob
f=" name "
t=${f##+([[:space:]])} # remove all leading white space
echo "[${t%%+([[:space:]])}]"
x="aaa-bbb---ccc"
echo "${x//+(-)/-}" # replace each run of dashes with one dash
[name]
aaa-bbb-ccc
Recursive Matching with globstar
With shopt -s globstar, the pattern ** used as a whole path component matches any number of folders, including none. Without the option, ** behaves like *:
echo **/*.js # globstar off: same as */*.js
shopt -s globstar
echo **/*.js # globstar on: every .js file at any depth
echo src/**/ # every folder inside src, including src itself
src/main.js
app.js app.min.js app.test.js src/lib/util.js src/lib/util.test.js src/main.js
src/ src/lib/
**/*.js replaces many simple uses of find . -name '*.js' (lesson 20), and it combines with extended globbing: **/!(*.test).js selects every JavaScript file that is not a test. For very large trees, or when you need conditions such as size or age, find remains the better tool.
Options That Change Matching
| Option | Effect |
|---|---|
extglob | enables ?() *() +() @() !() |
globstar | ** matches across folders |
nullglob | a pattern with no match expands to nothing |
failglob | a pattern with no match is an error |
dotglob | patterns also match names starting with . |
nocaseglob | filename expansion ignores letter case |
nocasematch | [[ ]] and case ignore letter case |
echo *env*; shopt -s dotglob; echo *env*; shopt -u dotglob
echo *.jpg; shopt -s nocaseglob; echo *.jpg; shopt -u nocaseglob
*env*
.env
*.jpg
photo.JPG
The first echo in each pair shows the default behaviour: a pattern that matches nothing is left unchanged, so the literal text *env* or *.jpg is printed. This default is dangerous in loops:
for f in *.xyz; do echo "got $f"; done
shopt -s nullglob
for f in *.xyz; do echo "got $f"; done; echo "(none)"
got *.xyz
(none)
Without nullglob, the loop ran once with the literal pattern as the "file name". With nullglob, the loop did not run at all. failglob turns the same situation into an error that stops the command:
$ bash -O failglob -c 'echo *.xyz; echo after'
bash: line 1: no match: *.xyz
Excluding Names with GLOBIGNORE
The variable GLOBIGNORE holds a colon-separated list of patterns. Names that match any of them are removed from the results of filename expansion:
GLOBIGNORE='*.min.js:*.test.js'
echo *.js
unset GLOBIGNORE
app.js
Setting GLOBIGNORE also turns on dotglob as a side effect, so unset it as soon as you no longer need it. For a single command, !(...) is usually clearer.
Quoting and Patterns
Quoting decides whether characters are pattern characters or literal text. On the right side of [[ == ]], an unquoted variable is used as a pattern, and a quoted one as a literal string:
s='a*'
[[ abc == $s ]] && echo "pattern match"
[[ abc == "$s" ]] || echo "literal no match"
pattern match
literal no match
When you compare user input with a fixed value, quote it. When you deliberately store a pattern in a variable, leave that variable unquoted on the right side.
Glob Patterns vs. Regular Expressions
[[ string =~ regex ]] (lesson 69) uses regular expressions instead of glob patterns. Regular expressions are more powerful: they support counted repetition ({4}), anchors and capture groups stored in BASH_REMATCH:
[[ 2026-11-24 =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]] && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"
2026 11
| Need | Use |
|---|---|
| select files | glob patterns (with extglob and globstar) |
| simple shape checks: extension, prefix, "all digits" | glob patterns in [[ == ]] or case |
| exact counts, alternation with structure, extracting parts | regular expressions with =~ |
Glob patterns always match the whole string, while a regular expression matches anywhere unless you anchor it with ^ and $.
A Complete Example: Checking File Names in a Project
check-names.sh walks through a project with ** and checks every file name against a set of naming rules, using extended patterns in both case and [[ ]]. It reports leftover backup files, committed environment files, white space, upper-case letters, unusual characters, non-standard extensions and missing extensions. The exit status makes it usable as a pre-commit check or a CI step.
#!/usr/bin/env bash
# check-names.sh: check file names in a project against naming rules
# usage: check-names.sh [DIR]
# Exit status: 0 if every name follows the rules, 1 if problems were found.
set -uo pipefail
shopt -s extglob globstar nullglob dotglob # before any code that uses the patterns
root=${1:-.}
cd -- "$root" || exit 2
problems=0
flag() { # flag FILE MESSAGE
printf '%-28s %s\n' "$1" "$2"
problems=$((problems + 1))
}
for path in **; do
[[ -f $path ]] || continue # regular files only
case $path in
.git/*|node_modules/*) continue ;; # skip tool folders
esac
name=${path##*/}
case $name in
*~|*.@(bak|orig|rej|swp|tmp))
flag "$path" "leftover backup or editor file"; continue ;;
.env.example)
continue ;; # a template without secrets
.env?(.*))
flag "$path" "environment file: must not be committed"; continue ;;
.*)
continue ;; # other dotfiles are allowed
@(README|LICENSE|CHANGELOG|Makefile|Dockerfile)?(.*))
continue ;; # conventional upper-case names
esac
if [[ $name == *[[:space:]]* ]]; then
flag "$path" "contains whitespace"
elif [[ $name == *[[:upper:]]* ]]; then
flag "$path" "contains upper-case letters"
elif [[ $name != +([a-z0-9_.-]) ]]; then
flag "$path" "contains characters outside a-z 0-9 _ . -"
elif [[ $name == *.@(jpeg|htm|yml) ]]; then
flag "$path" "non-standard extension"
elif [[ $name != *.* && $path != bin/* ]]; then
flag "$path" "no file extension"
fi
done
if (( problems > 0 )); then
printf '\n%d problem(s) found in %s\n' "$problems" "$root"
exit 1
fi
echo "All file names in $root follow the rules."
How It Works
- The
shoptline comes before every pattern that needs it.extglobenables the operators,globstarmakes**recursive,nullglobmakes an empty folder produce an empty loop, anddotglobincludes hidden files so that.envcan be checked. for path in **lists every file and folder below the root.[[ -f $path ]]keeps regular files only. The firstcaseskips the contents of.gitandnode_modules, which belong to tools, not to the project.${path##*/}extracts the file name from the path (lesson 152).- The second
casehandles names that need a decision before the general rules. Order matters:.env.exampleis allowed before.env?(.*)flags.envand.env.local, and the general.*branch allows other dotfiles such as.gitignore.@(README|LICENSE|...)?(.*)allows conventional names likeREADME.mdandMakefile, with or without an extension. - The
if/elifchain reports only the first problem per file, so the report stays short.*[[:space:]]*finds white space anywhere in the name,*[[:upper:]]*finds upper-case letters, and+([a-z0-9_.-])describes an allowed name completely, so!=catches anything else.*.@(jpeg|htm|yml)flags the less common spellings of.jpg,.htmland.yaml. Files inbin/may have no extension, because executables usually do not. flagprints one aligned line and counts the problem. The final status is 1 when anything was flagged, 2 when the folder cannot be entered, and 0 when every name is clean.
Running the Complete Example
The project folder proj contains a mix of good and bad names, including a .git folder and a node_modules folder with an upper-case file name that must be ignored:
./check-names.sh proj; echo "status $?"
.env environment file: must not be committed
.env.local environment file: must not be committed
assets/img/logo.jpeg non-standard extension
assets/img/logo@2x.png contains characters outside a-z 0-9 _ . -
assets/img/team photo.png contains whitespace
config.yml non-standard extension
docs.htm non-standard extension
notes no file extension
src/app.js~ leftover backup or editor file
src/components/NavBar.js contains upper-case letters
src/index.html.orig leftover backup or editor file
src/util (old).js contains whitespace
12 problem(s) found in proj
status 1
Files that follow the rules, such as README.md, LICENSE, Makefile, .gitignore, .env.example, package.json, src/app.js, src/components/footer.js and bin/deploy, do not appear. Neither does node_modules/x/Index.js. Because the loop expands ** in sorted order, the report lists paths alphabetically.
A clean project and a missing folder:
./check-names.sh clean; echo "status $?"
./check-names.sh nope; echo "status $?"
All file names in clean follow the rules.
status 0
./check-names.sh: line 9: cd: nope: No such file or directory
status 2