Pattern Matching and Extended Globbing

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 153 of 205

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

ContextExampleWhat the pattern is matched against
Filename expansionls *.lognames of files on disk
[[ ]] with == or !=[[ $file == *.log ]]a string
casecase $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

PatternMatches
*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:

ClassCharacters
[: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 |.

OperatorMatches
?(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 of js or css.
  • !(*.js): every name that does not end in .js. The result includes the folders docs and src, because filename expansion matches every kind of entry, not just files. Hidden files such as .env are still excluded, as with any pattern.
  • !(*.min).js: the part before .js must not itself end in .min, so app.min.js is excluded.
  • !(*.@(min|test)).js: operators can be nested; this excludes both minified and test files.
  • photo?(2).*: photo, an optional 2, 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

OptionEffect
extglobenables ?() *() +() @() !()
globstar** matches across folders
nullgloba pattern with no match expands to nothing
failgloba pattern with no match is an error
dotglobpatterns also match names starting with .
nocaseglobfilename 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
NeedUse
select filesglob patterns (with extglob and globstar)
simple shape checks: extension, prefix, "all digits"glob patterns in [[ == ]] or case
exact counts, alternation with structure, extracting partsregular 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 shopt line comes before every pattern that needs it. extglob enables the operators, globstar makes ** recursive, nullglob makes an empty folder produce an empty loop, and dotglob includes hidden files so that .env can be checked.
  • for path in ** lists every file and folder below the root. [[ -f $path ]] keeps regular files only. The first case skips the contents of .git and node_modules, which belong to tools, not to the project.
  • ${path##*/} extracts the file name from the path (lesson 152).
  • The second case handles names that need a decision before the general rules. Order matters: .env.example is allowed before .env?(.*) flags .env and .env.local, and the general .* branch allows other dotfiles such as .gitignore. @(README|LICENSE|...)?(.*) allows conventional names like README.md and Makefile, with or without an extension.
  • The if/elif chain 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, .html and .yaml. Files in bin/ may have no extension, because executables usually do not.
  • flag prints 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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Pattern Matching and Extended Globbing and get answers drawn from it.

Signed-in readers only.