Using case Statements

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

An if and elif chain is the right tool when each branch depends on a different condition. When one value must be compared against many possible answers, the chain becomes long and repetitive. The case statement was designed for exactly that job. It takes a single value, compares it with a list of patterns, and runs the commands attached to the first pattern that matches. It is the usual way to write menus, to handle commands such as start and stop, and to sort file names by extension.

Understanding the Concept

A case statement asks one question, "what is this value?", and offers several labeled answers. Compare the two styles for a script that reacts to the word in $1:

if [ "$1" = "start" ]; then
    echo "Starting service"
elif [ "$1" = "stop" ]; then
    echo "Stopping service"
elif [ "$1" = "restart" ]; then
    echo "Restarting service"
else
    echo "unknown command"
fi

The same logic as a case statement needs the subject only once:

case "$1" in
    start)   echo "Starting service" ;;
    stop)    echo "Stopping service" ;;
    restart) echo "Restarting service" ;;
    *)       echo "unknown command" ;;
esac

The second form is shorter and easier to scan, and adding a new command means adding one line. A case statement also supports wildcard patterns and several alternatives per branch, which a chain of = comparisons cannot express without extra work.

Syntax

case WORD in
    PATTERN1)
        commands
        ;;
    PATTERN2 | PATTERN3)
        commands
        ;;
    *)
        commands
        ;;
esac

The parts are:

  • case starts the statement and esac (which is case spelled backwards) ends it.
  • WORD is the value being tested. It is expanded first, so it can be a variable, a command substitution, or plain text.
  • in separates the word from the list of branches.
  • Each branch begins with one or more patterns, separated by |, and a closing parenthesis ).
  • The commands of a branch follow the parenthesis and may span many lines.
  • Two semicolons, ;;, end the branch.
  • The pattern * matches anything, which makes it the natural default branch. It belongs last, because the first matching pattern wins.

Short branches can sit on one line, with the ;; at the end. Longer branches are usually written with the commands on their own lines, indented one level deeper than the pattern.

Basic Example

fruit="apple"

case "$fruit" in
    apple)  echo "red or green" ;;
    banana) echo "yellow" ;;
    *)      echo "unknown fruit" ;;
esac

Output:

red or green

Running the same statement for several values shows the other branches:

for fruit in apple banana kiwi; do
    case "$fruit" in
        apple)  echo "$fruit: red or green" ;;
        banana) echo "$fruit: yellow" ;;
        *)      echo "$fruit: unknown fruit" ;;
    esac
done

Output:

apple: red or green
banana: yellow
kiwi: unknown fruit

Understanding the Example

When Bash reaches case "$fruit" in, it first expands the word. With fruit=apple, the word becomes apple. It then reads the patterns from top to bottom and compares the word with each. The pattern apple matches, so Bash runs echo "red or green" and, at the ;;, leaves the statement. It does not look at the remaining patterns. For kiwi, neither apple nor banana matches, but * matches everything, so the default branch runs.

The for loop in the second part (covered in lesson 78) repeats the statement for three values. Each pass runs exactly one branch.

How Matching Works

The patterns in a case statement are shell patterns, the same wildcard patterns used for file names (lesson 52). They are not regular expressions. The most useful pieces are:

PatternMatches
abcexactly the text abc
*any text, including an empty string
?exactly one character
[abc]one character from the set
[a-z]one character from the range
[[:digit:]]one character from a named class such as digits
a|beither a or b (alternatives, written with a plain | between patterns)

The whole word must match the whole pattern. The pattern app does not match apple, but app* does. Lesson 76 covers pattern matching in depth, including extended patterns.

Alternatives with |

One branch can answer to several spellings:

for ans in y Y yes YES n No maybe; do
    case "$ans" in
        y|Y|yes|YES) echo "$ans -> yes" ;;
        n|N|no|NO)   echo "$ans -> no" ;;
        *)           echo "$ans -> unrecognized" ;;
    esac
done

Output:

y -> yes
Y -> yes
yes -> yes
YES -> yes
n -> no
No -> unrecognized
maybe -> unrecognized

The pipe character here is not a pipeline. Inside the pattern list, it separates alternative patterns. Note that No is not accepted, since the list contains no and NO but not No. Patterns are case-sensitive, which is why the listing must name every spelling or use one of the techniques shown in the section on case-insensitive matching.

Wildcards and Character Sets

A single statement can classify file names, with each branch using a different kind of pattern:

for f in report.txt photo.png data.csv README archive.tar.gz .hidden ""; do
    case "$f" in
        *.txt)           t="text" ;;
        *.png|*.jpg)     t="image" ;;
        *.tar.gz|*.tgz)  t="archive" ;;
        .*)              t="hidden" ;;
        [A-Z]*)          t="starts with capital" ;;
        "")              t="empty" ;;
        *)               t="other" ;;
    esac
    echo "[$f] -> $t"
done

Output:

[report.txt] -> text
[photo.png] -> image
[data.csv] -> other
[README] -> starts with capital
[archive.tar.gz] -> archive
[.hidden] -> hidden
[] -> empty

Every name ends up in exactly one branch. data.csv matches nothing before *, so it lands in the default. README has no extension but begins with a capital letter, so [A-Z]* catches it. The empty string matches only the pattern "", which is a pair of quotes with nothing between them. The pattern * would also match an empty string, but because "" comes first, it is chosen instead.

The question-mark and bracket patterns work the same way:

for c in a ab abc; do
    case "$c" in
        ?)   echo "$c: one char" ;;
        ??)  echo "$c: two chars" ;;
        *)   echo "$c: longer" ;;
    esac
done

for c in 7 x Q; do
    case "$c" in
        [0-9])        echo "$c: digit" ;;
        [a-z])        echo "$c: lowercase" ;;
        [[:upper:]])  echo "$c: uppercase" ;;
    esac
done

Output:

a: one char
ab: two chars
abc: longer
7: digit
x: lowercase
Q: uppercase

The First Match Wins

Patterns are checked in order, and the search stops at the first match. When two patterns could both match, the order decides:

v=abc

case "$v" in
    a*)  echo "first: a*" ;;
    abc) echo "second: abc" ;;
    *)   echo "default" ;;
esac

Output:

first: a*

The value abc matches both a* and abc, but the broader pattern comes first, so the more specific one is never reached. Place specific patterns before general ones, and keep * at the very end.

Quoting Inside case

Quoting changes whether a character is a wildcard, just as it does in filenames. A quoted asterisk is an ordinary character:

case 'a*' in "a*") echo "quoted star is literal and matches a*" ;; esac
case "abc" in "a*") echo "wrong" ;; *) echo "quoted star does not match abc" ;; esac

Output:

quoted star is literal and matches a*
quoted star does not match abc

The same rule applies to a pattern stored in a variable. Unquoted, the variable's value is used as a pattern. Quoted, it is compared as plain text:

pat='a*'

case "abc" in "$pat") echo "matches" ;; *) echo "quoted variable: literal text, no match" ;; esac
case "abc" in $pat)   echo "unquoted variable: pattern, matches abc" ;; *) echo "no" ;; esac

Output:

quoted variable: literal text, no match
unquoted variable: pattern, matches abc

This matches what [[ ]] does with the right side of == (lesson 69). Quote the pattern part to force an exact comparison, and leave it unquoted when you want wildcards.

The word after case, unlike a command argument, does not undergo word splitting or filename expansion. A value with spaces stays together even without quotes, and an unset variable becomes an empty string:

s="hello world"
case $s in "hello world") echo "matched with spaces" ;; esac

unset u
case $u in "") echo "unquoted unset variable works too" ;; esac

Output:

matched with spaces
unquoted unset variable works too

Even so, quoting the word, as in case "$s" in, is a good habit because it works the same way in every context and reads consistently.

Exit Status of a case Statement

A case statement returns the status of the last command it ran. If no pattern matched and there was no default, it returns 0:

case "zzz" in
    a) echo "a" ;;
    b) echo "b" ;;
esac
echo "status with no match: $?"

case x in x) false ;; esac; echo "status after false: $?"
case x in x) true ;;  esac; echo "status after true: $?"
case x in x) ;;       esac; echo "status of an empty branch: $?"

Output:

status with no match: 0
status after false: 1
status after true: 0
status of an empty branch: 0

Because a missing match is not an error, a script that must react to unexpected values needs an explicit default branch with *). Without it, a typo in an argument passes silently.

Terminators: ;;, ;& and ;;&

The usual terminator ;; ends the statement as soon as a branch has run. Bash has two more terminators, which change what happens next:

TerminatorEffect after the branch runs
;;stop; leave the case statement
;&continue into the next branch's commands without testing its pattern
;;&continue testing the remaining patterns; run any that also match
n=1

case $n in
    1) echo "one" ;&
    2) echo "two (fall through)" ;;
    3) echo "three" ;;
esac

Output:

one
two (fall through)

The ;& after the first branch makes Bash run the commands of the next branch even though n is not 2. The second branch ends with ;;, so three never runs.

case "ab" in
    a*) echo "matches a*" ;;&
    *b) echo "matches *b" ;;&
    *)  echo "matches *" ;;
esac

Output:

matches a*
matches *b
matches *

Here ;;& tells Bash to keep checking. The word ab matches all three patterns, so all three branches run. These two terminators exist only in Bash, so scripts that must run under sh should avoid them.

Missing the terminator on the last branch is allowed, because the esac ends the statement anyway:

case y in
    y) echo "no terminator on last branch"
esac

Output:

no terminator on last branch

Adding ;; on every branch, including the last, keeps the code uniform and makes it safe to add new branches later.

Syntax Errors to Recognize

Forgetting a closing parenthesis or ;; produces errors that look unrelated to the real cause:

case x in x) echo hi esac

Output:

bash: -c: line 2: syntax error: unexpected end of file

Here esac was read as an argument to echo, because the branch has no ;; or newline before it, so the statement never ends. The -c in the message appears because this command was given to bash -c; in a script file, the script name and line number appear in its place.

case x in x echo hi;; esac

Output:

bash: -c: line 1: syntax error near unexpected token `echo'

The pattern x has no closing parenthesis, so Bash sees echo where it expected ).

Case-Insensitive Matching

Because patterns are case-sensitive, there are three common ways to accept yes, Yes and YES. The first is to name each letter's two forms in a bracket expression:

case "YES" in [yY][eE][sS]) echo "bracket form matched" ;; esac

Output:

bracket form matched

The second is to lowercase the value first with the ${var,,} expansion (lesson 70):

answer="YeS"
case "${answer,,}" in yes) echo "lowercased matched" ;; esac

Output:

lowercased matched

The third is the nocasematch shell option, which makes both case and [[ ]] ignore case until it is turned off again:

shopt -s nocasematch
case "YES" in yes) echo "nocasematch: matched" ;; esac
shopt -u nocasematch

case "YES" in yes) echo "bad" ;; *) echo "case-sensitive again: no match" ;; esac

Output:

nocasematch: matched
case-sensitive again: no match

Remember to switch the option off afterwards, so that later case statements in the script behave normally. The shopt command is covered in lesson 149.

Numbers Are Matched as Text

A case statement compares text only. It has no concept of numeric value, so 07 and 7 are different:

case 07 in
    7)  echo "07 matches 7" ;;
    07) echo "07 matches 07 as text" ;;
esac

Output:

07 matches 07 as text

For comparisons such as "greater than ten", use the integer operators from lesson 73. A case statement is best for exact values, lists of values and shapes of text.

Portability

The core syntax, case, in, patterns, |, ), ;; and esac, is part of the POSIX standard and works in every shell. Run through Dash, the examples with alternatives, wildcards and bracket expressions all produced the expected output:

dash alt ok
dash glob ok
dash bracket ok

The ;& and ;;& terminators are not portable. Dash rejects ;&:

sh: 1: Syntax error: "&" unexpected

This is another reason case is often preferred over [[ ]] for scripts that must run under sh. It gives pattern matching without needing [[.

Practical Applications

A service-style script that acts on its first argument and rejects anything else with a usage message:

#!/usr/bin/env bash

case "$1" in
    start)   echo "Starting service" ;;
    stop)    echo "Stopping service" ;;
    restart) echo "Restarting service" ;;
    status)  echo "Service is running" ;;
    "")      echo "usage: $0 {start|stop|restart|status}" >&2; exit 2 ;;
    *)       echo "unknown command: $1" >&2; exit 2 ;;
esac

Saved as cmd.sh, the script prints Starting service for bash cmd.sh start and exits with status 0. With no argument, it prints usage: cmd.sh {start|stop|restart|status} to standard error and exits with status 2. With bogus, it prints unknown command: bogus and also exits with status 2. Handling the empty string separately gives a more helpful message than the generic default. Lesson 127 builds on this pattern when parsing script arguments, and lesson 130 introduces getopts for options.

A script that reports what kind of file each argument is, based on its extension:

for f in "$@"; do
    case "$f" in
        *.jpg|*.jpeg|*.png|*.gif) echo "$f: image" ;;
        *.mp3|*.wav)              echo "$f: audio" ;;
        *.sh)                     echo "$f: shell script" ;;
        *.tar.gz|*.zip)           echo "$f: archive" ;;
        *)                        echo "$f: unknown type" ;;
    esac
done

Run with cat.jpg song.mp3 run.sh backup.tar.gz notes.txt "my photo.png", it printed:

cat.jpg: image
song.mp3: audio
run.sh: shell script
backup.tar.gz: archive
notes.txt: unknown type
my photo.png: image

The quoted "$f" keeps the name with a space in it as one value. The extension .tar.gz is listed as one pattern, which works because * matches any text before it.

A script that adapts to the operating system by testing the output of a command. The $(...) substitution comes from lesson 48:

case "$(uname -s)" in
    Linux)  echo "running on Linux" ;;
    Darwin) echo "running on macOS" ;;
    *)      echo "other OS" ;;
esac

On the test machine the output was running on Linux. On macOS, uname -s prints Darwin, which is why that word appears in the second branch.

A case statement inside a loop, using continue to skip some values. Loop control is covered in lesson 84:

for n in 1 2 3 4 5; do
    case $n in
        2|4) continue ;;
    esac
    echo "n=$n"
done

Output:

n=1
n=3
n=5

The values 2 and 4 match the first branch, and continue jumps back to the top of the loop before the echo runs. For values with no matching branch, the statement does nothing, so the echo executes. The same pattern is the basis of menus built with read (lesson 31) and select (lesson 86).

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

Signed-in readers only.