Pattern Matching in case

Su Suriya Ravichandran Updated 06 Dec 2026
16 min read ·Lesson 76 of 205

Lesson 75 showed that a case branch starts with a pattern and that the first pattern matching the word wins. Almost every real script needs more than a plain word or a trailing *: it has to accept a whole family of values, such as any image extension, any option that starts with a dash, or any string made only of digits. This lesson looks closely at the pattern language itself. It covers bracket expressions, character classes, the way * treats slashes and dots, quoting inside patterns, and the extended patterns that Bash adds with the extglob option.

What a case Pattern Is

A case pattern is a shell pattern, the same wildcard language used to match file names (lesson 52). It is not a regular expression. The important point is that the pattern must match the entire word, from the first character to the last. The basic building blocks are:

ElementMeaning
*any run of characters, including none
?exactly one character
[abc]one character from the listed set
[a-f]one character from a range
[!abc]one character that is not in the set
[[:digit:]]one character from a named class
0 or '*'a literal star

The rest of the lesson works through each of these, then moves on to the extended forms that are off by default.

Bracket Expressions in Depth

A bracket expression stands for exactly one character. It can list characters, give ranges, or negate the set:

for c in a Z 5 _ ""; do
    case "$c" in
        [a-z])        echo "[$c] lowercase" ;;
        [A-Z])        echo "[$c] uppercase" ;;
        [0-9])        echo "[$c] digit" ;;
        [!a-zA-Z0-9]) echo "[$c] other single char" ;;
        *)            echo "[$c] something else" ;;
    esac
done

Output:

[a] lowercase
[Z] uppercase
[5] digit
[_] other single char
[] something else

The underscore is neither a letter nor a digit, so it reaches the negated set [!a-zA-Z0-9]. The empty string cannot match any bracket expression, because a bracket expression always consumes one character, so it falls through to *.

Bash accepts both [!...] and [^...] for negation:

case "x" in
    [^abc]) echo "x is not a, b or c" ;;
esac

Output:

x is not a, b or c

The [!...] form is the one defined by the POSIX standard, and it works everywhere. The [^...] form is a Bash extension. Under Dash, a ^ at the start of a set is treated as an ordinary member of the set, so case "^" in [^abc]) ... matches the caret itself while case "x" in [^abc]) ... does not match. Use [!...] in any script that may run under sh.

Special Characters Inside a Set

A few characters have a special role only at certain positions inside the brackets:

case "]" in []]) echo "] first in set" ;; esac
case "-" in [a-]) echo "- last in set" ;; esac
case "x" in [!]]) echo "negated ]" ;; esac

Output:

] first in set
- last in set
negated ]

A closing bracket placed first (after any !) is a member of the set rather than the end of it. A dash placed first or last is a plain dash rather than a range operator.

Named Character Classes

Ranges such as [a-z] depend on how the locale orders characters. Named classes describe the same sets in a way that does not depend on the locale. The class name is written between [: and :], and that whole item sits inside the outer brackets, which is why you see double brackets:

ClassMatches
[[:digit:]]decimal digits
[[:alpha:]]letters
[[:alnum:]]letters and digits
[[:upper:]]uppercase letters
[[:lower:]]lowercase letters
[[:space:]]space, tab, newline and similar
[[:punct:]]punctuation

A pattern can combine a class with * to test the contents of a string. The next example classifies a value by looking for any character that is not a digit:

for s in 2026 abc A1 "a b" ""; do
    case "$s" in
        "")             echo "[$s] empty" ;;
        *[![:digit:]]*)
            case "$s" in
                *[[:space:]]*)  echo "[$s] contains a space" ;;
                *[![:alpha:]]*) echo "[$s] mixed" ;;
                *)              echo "[$s] letters only" ;;
            esac ;;
        *)              echo "[$s] digits only" ;;
    esac
done

Output:

[2026] digits only
[abc] letters only
[A1] mixed
[a b] contains a space
[] empty

The pattern *[![:digit:]]* reads as "anything, then one character that is not a digit, then anything". If the value contains such a character, the first inner case looks closer. If the value does not, the branch is skipped and the final *) branch means every character was a digit. The inner case shows that one statement can sit inside a branch of another.

In the C and C.UTF-8 locales that were tested, B is not matched by [a-z] and b is matched by [[:lower:]]. Other locales may order letters differently, so the named classes are the safer choice when a script runs on machines you do not control.

Slashes and Leading Dots Are Not Special

Filename expansion refuses to let * cross a / or match a leading dot. A case statement compares plain strings, so neither restriction applies:

case "/var/log/app.log" in /var/*) echo "star matches slashes" ;; esac
case ".hidden" in *) echo "star matches leading dot" ;; esac
case ".hidden" in ?hidden) echo "question mark matches leading dot" ;; esac

Output:

star matches slashes
star matches leading dot
question mark matches leading dot

This is convenient when the word is a path. The pattern /var/* matches /var/log/app.log even though the path has two more slashes after /var/. It also means a pattern such as *.log matches .log itself, because the part before the dot may be empty.

Quoting and Escaping Inside Patterns

Any pattern character becomes an ordinary character when it is quoted or preceded by a backslash:

case 'a*b' in a\*b) echo "escaped star is literal" ;; esac
case 'a?b' in 'a?b') echo "quoted question mark is literal" ;; esac
case 'ab'  in 'a?b') echo "wrong" ;; *) echo "quoted ? does not match ab" ;; esac
case '-v'  in -v)    echo "leading dash pattern fine" ;; esac

Output:

escaped star is literal
quoted question mark is literal
quoted ? does not match ab
leading dash pattern fine

The word -v as a pattern needs no special treatment. Because case is a compound command and not an ordinary command, a leading dash is never mistaken for an option, which is why option parsers can write branches such as -v|--verbose) directly.

You can also mix quoted and unquoted parts in one pattern. The quoted part is taken literally and the unquoted part keeps its wildcard meaning:

dir='/tmp/my dir'
case "/tmp/my dir/a.txt" in "$dir"/*.txt) echo "quoted prefix, glob suffix" ;; esac

Output:

quoted prefix, glob suffix

The variable dir contains a space and could contain characters such as * or [. Quoting it makes sure the directory name is compared as plain text, while *.txt after it still works as a wildcard.

Patterns Stored in Variables

An unquoted variable expands to text that is then treated as a pattern. A quoted one is compared literally:

pat='*.txt'
case "notes.txt" in $pat)   echo "unquoted var is a pattern" ;; esac
case "notes.txt" in "$pat") echo "wrong" ;; *) echo "quoted var is literal" ;; esac

Output:

unquoted var is a pattern
quoted var is literal

This is the same rule that applies to the right side of == inside [[ ]] (lesson 69). Quote a variable when its contents are data and leave it unquoted only when the variable deliberately holds a pattern.

Extended Patterns with extglob

The basic language cannot say "one or more digits", "either of these two words, but nothing else", or "anything except this". Bash adds five extra forms for this, called extended patterns or extglob patterns. Each one wraps a list of patterns, separated by |, in parentheses:

FormMatches
?(list)zero or one occurrence of any pattern in the list
*(list)zero or more occurrences
+(list)one or more occurrences
@(list)exactly one occurrence
!(list)anything except what the list matches

The forms are only recognized when the extglob shell option is on. Turn it on with shopt -s extglob (the shopt command gets its own lesson, number 149).

shopt -s extglob

for f in a.jpg b.png c.gif d.txt; do
    case "$f" in
        *.@(jpg|png|gif)) echo "$f image" ;;
        *)                echo "$f other" ;;
    esac
done

Output:

a.jpg image
b.png image
c.gif image
d.txt other

The pattern *.@(jpg|png|gif) means "anything, a dot, and then exactly one of jpg, png or gif". This replaces three alternatives that would otherwise be written as *.jpg|*.png|*.gif).

When the Option Must Be Turned On

Bash reads a script one complete command at a time, and it decides how to read the patterns when it parses that command. That has two consequences that surprise many people. First, the shopt -s extglob must be on a separate line that comes before the case. On the same line, the option is not yet active when the case is parsed:

#!/usr/bin/env bash
shopt -s extglob; case "a.png" in *.@(png|jpg)) echo "image" ;; esac

Output:

same_line.sh: line 2: syntax error near unexpected token `('
same_line.sh: line 2: `shopt -s extglob; case "a.png" in *.@(png|jpg)) echo "image" ;; esac'

Put the shopt on its own line and the same statement works, printing image.

Second, turning the option on inside a function does not help the code of that function, because the whole function body is parsed when the function is defined, before any of its commands run:

#!/usr/bin/env bash
check() {
    shopt -s extglob
    case "$1" in
        *.@(png|jpg)) echo "image" ;;
    esac
}
check a.png

Output:

in_function.sh: line 5: syntax error near unexpected token `('
in_function.sh: line 5: `        *.@(png|jpg)) echo "image" ;;'

The fix is to enable extglob at the top of the script, before the function definition. With the option off, any extended pattern is a plain syntax error, because the opening parenthesis has no meaning there:

ext_off.sh: line 3: syntax error near unexpected token `('
ext_off.sh: line 3: `    *.@(png|jpg)) echo "image" ;;'

Starting Bash with bash -O extglob script.sh also turns the option on before the file is read. In Dash, which has no such option, the extended forms are always a syntax error.

Optional Text with ?(...)

The form ?(list) makes part of a pattern optional:

shopt -s extglob

for w in color colour colr; do
    case "$w" in
        colo?(u)r) echo "$w ok" ;;
        *)         echo "$w no" ;;
    esac
done

Output:

color ok
colour ok
colr no

The u may appear zero or one times, so both spellings match. colr lacks the second o and is rejected.

Repetition with *(...) and +(...)

The form *(list) accepts any number of repetitions, including none, while +(list) needs at least one:

shopt -s extglob

for s in "" ab abab ababa; do
    case "$s" in
        *(ab)) echo "[$s] repeats of ab" ;;
        *)     echo "[$s] not only ab" ;;
    esac
done

for s in "" 7 2026 20a6; do
    case "$s" in
        +([0-9])) echo "[$s] integer digits" ;;
        *)        echo "[$s] not digits" ;;
    esac
done

Output:

[] repeats of ab
[ab] repeats of ab
[abab] repeats of ab
[ababa] not only ab
[] not digits
[7] integer digits
[2026] integer digits
[20a6] not digits

The empty string matches *(ab) because zero repetitions are allowed, but it does not match +([0-9]), which demands at least one digit. The pattern +([0-9]) is the extglob way of saying "only digits", and it is much shorter than the nested case shown earlier.

Exactly One with @(...)

The form @(list) matches one of the alternatives and nothing more. It is the natural way to accept a fixed set of words:

shopt -s extglob

for s in start stop startstop pause; do
    case "$s" in
        @(start|stop)) echo "$s command" ;;
        *)             echo "$s unknown" ;;
    esac
done

Output:

start command
stop command
startstop unknown
pause unknown

The value startstop is rejected because it is two alternatives glued together, and @(...) allows only one.

Anything Except with !(...)

The form !(list) matches every string that the list does not match:

shopt -s extglob

for f in main.c util.c main.h notes.txt; do
    case "$f" in
        !(*.c)) echo "$f not a .c file" ;;
        *)      echo "$f is a .c file" ;;
    esac
done

Output:

main.c is a .c file
util.c is a .c file
main.h not a .c file
notes.txt not a .c file

The negation covers the whole string, so !(yes|y) accepts any word other than yes and y:

shopt -s extglob

case "no" in
    !(yes|y)) echo "no -> not yes or y" ;;
    *)        echo "yes or y" ;;
esac

Output:

no -> not yes or y

A negation can also sit between fixed parts of a pattern. With test_!(b), the text after test_ may be anything except exactly b:

shopt -s extglob

for n in test_a test_b prod_a; do
    case "$n" in
        test_!(b)) echo "$n test but not b" ;;
        *)         echo "$n other" ;;
    esac
done

Output:

test_a test but not b
test_b other
prod_a other

Building Validators from Patterns

Combining the forms gives compact checks for the shape of a value. This function accepts an integer with an optional sign:

#!/usr/bin/env bash
shopt -s extglob

is_number() {
    case "$1" in
        ?([-+])+([0-9])) return 0 ;;
        *)               return 1 ;;
    esac
}

for x in 42 -7 +3 4.5 "" - abc 12a; do
    if is_number "$x"; then echo "[$x] integer"; else echo "[$x] not integer"; fi
done

Output:

[42] integer
[-7] integer
[+3] integer
[4.5] not integer
[] not integer
[-] not integer
[abc] not integer
[12a] not integer

The pattern ?([-+])+([0-9]) says "an optional plus or minus, followed by one or more digits". A lone - fails because the digits part needs at least one character. The function returns a status instead of printing, so it can be used directly in an if, as lesson 66 showed.

Alternatives with | let a single pattern describe two different shapes. This version accepts decimals such as 3.14, .5 and 5.:

is_decimal() {
    case "$1" in
        ?([-+])+([0-9])?(.*([0-9]))|?([-+]).+([0-9])) return 0 ;;
        *) return 1 ;;
    esac
}

for x in 3.14 -0.5 .5 5. 1.2.3 abc; do
    if is_decimal "$x"; then echo "[$x] decimal"; else echo "[$x] not decimal"; fi
done

Output:

[3.14] decimal
[-0.5] decimal
[.5] decimal
[5.] decimal
[1.2.3] not decimal
[abc] not decimal

The first alternative is a sign, digits, and an optional dot followed by more digits. The second alternative handles a number that starts with a dot. Both alternatives are separated by a plain | at the top level of the branch. Notice that is_decimal was defined in the same file as is_number, after shopt -s extglob had already run on its own line.

A dotted version number or an IPv4-looking address works the same way. Each group of digits is +([0-9]), and the dots are literal:

shopt -s extglob

for v in 1.2 1.2.3 10.20.30 1. a.b; do
    case "$v" in
        +([0-9]).+([0-9])?(.+([0-9]))) echo "$v version" ;;
        *)                             echo "$v not a version" ;;
    esac
done

for ip in 192.168.0.1 10.0.0 1.2.3.4.5; do
    case "$ip" in
        +([0-9]).+([0-9]).+([0-9]).+([0-9])) echo "$ip looks like ipv4" ;;
        *)                                   echo "$ip no" ;;
    esac
done

Output:

1.2 version
1.2.3 version
10.20.30 version
1. not a version
a.b not a version
192.168.0.1 looks like ipv4
10.0.0 no
1.2.3.4.5 no

The IPv4 pattern checks only the shape. It would accept 999.999.999.999, because it does not check that each number is at most 255. Patterns describe the form of a value, and arithmetic (lesson 73) is the right tool for checking its size.

Pattern Matching in Arguments

Option handling is a good fit for pattern matching, because options have a recognizable shape. This loop sorts each argument into a category:

for a in -v --verbose -- -x file.txt ""; do
    case "$a" in
        -v|--verbose) echo "[$a] verbose" ;;
        --)           echo "[$a] end of options" ;;
        -?*)          echo "[$a] unknown option" ;;
        "")           echo "[$a] empty" ;;
        *)            echo "[$a] operand" ;;
    esac
done

Output:

[-v] verbose
[--verbose] verbose
[--] end of options
[-x] unknown option
[file.txt] operand
[] empty

The order is what makes this correct. The specific words come first, so -- is recognized before the general pattern -?*, which means "a dash followed by at least one more character". Placing -?* first would swallow --verbose and -- as well. Lessons 127 and 130 build full argument parsers on this idea.

The first characters of a word can also be tested against a variable that holds a prefix. The variable is quoted so that it is compared as text, and the * after it stays a wildcard:

prefix="log_"
case "log_2026.txt" in
    "$prefix"*) echo "starts with prefix" ;;
esac

Output:

starts with prefix

Ignoring Case with nocasematch

All of these patterns are case-sensitive. The shell option nocasematch makes case ignore the difference between uppercase and lowercase letters, and it combines with extended patterns. The script below sorts its arguments by extension:

#!/usr/bin/env bash
shopt -s extglob nocasematch

for f in "$@"; do
    case "$f" in
        *.@(jpg|jpeg|png|gif)) echo "$f: image" ;;
        *.@(tar.gz|tgz|zip))   echo "$f: archive" ;;
        *.@(sh|bash))          echo "$f: script" ;;
        *)                     echo "$f: unknown" ;;
    esac
done

Running bash sort_files.sh a.JPG b.Tar.GZ "c d.sh" notes.txt x.PNG prints:

a.JPG: image
b.Tar.GZ: archive
c d.sh: script
notes.txt: unknown
x.PNG: image

The shopt -s extglob nocasematch line sets both options at once, and it is on its own line before any case. The quoted "c d.sh" is passed as one argument, so the space does not matter.

Without nocasematch, the same effect needs a bracket pair for each letter, such as *.[Jj][Pp][Gg], which grows quickly. Lesson 75 also showed lowercasing the value first with ${var,,}.

Using Patterns in [[ ]] Too

Extended patterns are not limited to case. The right side of == and != inside [[ ]] is the same pattern language, with the same extglob requirement:

shopt -s extglob

f=photo.png
[[ $f == *.@(png|jpg) ]] && echo "[[ ]] image"

Output:

[[ ]] image

This lets you reuse one pattern in either construct. The safest habit is the same for both: enable the option on its own line near the top of the script, before any code that uses extended patterns.

Portability

The basic patterns (*, ?, [...], [!...], [[:class:]], and alternatives with |) are part of the POSIX shell language and work in Dash and in sh generally. A leading parenthesis before the pattern list is also accepted:

case "go" in
    (go|run) echo "go or run" ;;
esac

This prints go or run in both Bash and Dash. Two things are specific to Bash: the [^...] negation, and everything built on extglob. A script that must run under sh should stick to [!...] and to basic patterns, and use several alternatives separated by | where an extended pattern would otherwise be used. Lessons 153, 188 and 189 return to extended globbing and to the differences between Bash and POSIX shell syntax.

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 in case and get answers drawn from it.

Signed-in readers only.