case Statements and select Menus

case Statements and select Menus in Bash: --- Behind the counter of an old sorting office stands a wooden frame of pigeonholes, and in front of it stands a…


The Analogy: The Postal Sorting Frame

Behind the counter of an old sorting office stands a wooden frame of pigeonholes, and in front of it stands a sorter with a stack of letters. The frame is not a random grid; the slots are arranged in a deliberate order, each labelled with a rule. The top slots hold the most specific rules -- "postcode begins SW1, priority" -- and the lower slots hold broader ones -- "anything for the south-west", "anything at all". The sorter takes each letter, reads the address once, and runs down the frame from the top, dropping the letter into the first slot whose rule it satisfies. The moment a letter lands, that letter is done; the sorter does not keep checking the lower slots for it.

This is exactly how a case statement works. You hand it one value -- a filename, a command word, a status code -- and it runs down a list of patterns in the order you wrote them, executing the body of the first pattern that matches and then stopping. The specificity ordering matters for the same reason it matters on the frame: if the broad "anything at all" slot sat at the top, every letter would land there and the specific slots would never be reached. A case whose catch-all pattern comes first, or whose *.tar.gz rule sits below its *.gz rule, misroutes in precisely this way.

The frame has one more feature that a plain if ladder lacks: the slots are labelled with patterns, not exact strings. A single slot can say "any postcode starting SW", covering thousands of addresses, and another can say "SW1 or SW2 or SW3" on one label. case patterns are shell globs with the same reach: *.txt matches any text file, start|stop|status matches any of three words on one branch, and a bracket class matches a range. This is what makes case the natural tool for classifying a value into one of several shapes, where an if chain of string comparisons would be a wall of repetition.

The failure mode is the misordered or too-greedy label. If a letter for "SW1A priority" reaches a broad "south-west" slot before its specific slot because the specific one was placed too low, it still gets delivered -- just to the wrong, slower stream, and nobody notices because nothing was rejected. In the shell this is the silent bug: a case that matches an earlier, broader pattern runs the wrong branch and returns cleanly, so the script carries on with the wrong action taken. The whole discipline of writing a case is ordering patterns from most specific to most general, and knowing exactly where the matching stops.


Syntax or Core Structure

A case statement takes a word, matches it against a series of glob patterns each ending in ), runs the body of the first match, and closes with esac. Each branch normally ends in ;;, which means "stop here". The classic use is classifying a value, and the classic bug is pattern order, so this example puts the most specific patterns first.

#!/usr/bin/env bash
classify() {
  case $1 in
    *.tar.gz|*.tgz) printf '%-14s gzipped tarball\n' "$1" ;;
    *.tar)          printf '%-14s plain tarball\n' "$1" ;;
    *.gz)           printf '%-14s gzip file\n' "$1" ;;
    *.txt|*.md)     printf '%-14s text document\n' "$1" ;;
    *.[0-9])        printf '%-14s numbered file\n' "$1" ;;
    *)              printf '%-14s unknown\n' "$1" ;;
  esac
}
for f in backup.tar.gz notes.md data.tar archive.gz page.3 readme; do
  classify "$f"
done

The pattern *.tar.gz sits above *.gz on purpose: backup.tar.gz matches both, and because case stops at the first match, the specific one must come first or every tarball would be mislabelled a plain gzip file. The | joins alternative patterns on one branch, [0-9] is a bracket class, and the final * is the catch-all that guarantees every value lands somewhere.

Output:

backup.tar.gz  gzipped tarball
notes.md       text document
data.tar       plain tarball
archive.gz     gzip file
page.3         numbered file
readme         unknown

Technical Depth: Terminators, Matching Rules, and the Menu Builder

The three branch terminators

Most branches end in ;;, but bash offers two others that change what happens after a match. ;; stops. ;& falls through into the next branch's body without testing its pattern. ;;& stops running the current body but continues testing the remaining patterns against the same value.

TerminatorAfter running the bodyUse when
;;stop, leave the casethe branches are mutually exclusive
;&run the next body unconditionallyone branch should include the next
;;&keep testing later patternsseveral independent tags may all apply

The fall-through ;& is useful for severity levels that nest: a critical event should also do everything an error does.

#!/usr/bin/env bash
level=$1
case $level in
  critical) printf 'paging on-call\n'       ;&
  error)    printf 'writing to error log\n' ;&
  warn)     printf 'writing to main log\n'  ;;
  info)     printf 'main log only\n'        ;;
esac

Output:

paging on-call
writing to error log
writing to main log

That output is for an argument of critical: it runs its own body and then falls through error and warn because each ends in ;&, stopping at the ;; on warn. Call it with warn and only the single line writing to main log prints. The ;;& terminator does the opposite job -- it keeps testing -- which lets one value collect several independent labels.

#!/usr/bin/env bash
tag=$1
case $tag in
  *[0-9]*) printf 'contains a digit\n'       ;;&
  *[a-z]*) printf 'contains a lowercase\n'   ;;&
  *_*)     printf 'contains an underscore\n' ;;&
  *)       printf 'done scanning\n'          ;;
esac

Output:

contains a digit
contains a lowercase
contains an underscore
done scanning

For the argument ab_12 all three tests pass and the catch-all runs too, because ;;& sends the shell on to re-test each remaining pattern rather than leaving the case. This turns a case into a set of independent checks against one value, which is occasionally exactly what you want.

Case-sensitivity is a shell option

Pattern matching in case is case-sensitive by default. The nocasematch shell option flips that for both case and [[, and because it is a global toggle you should set it and unset it around the specific block that needs it.

#!/usr/bin/env bash
match() {
  case $1 in
    yes) printf '%s matched yes\n' "$1" ;;
    *)   printf '%s did not match\n' "$1" ;;
  esac
}
shopt -u nocasematch
match YES
shopt -s nocasematch
match YES
shopt -u nocasematch

Output:

YES did not match
YES matched yes

The same input YES misses the yes pattern under the default and hits it once nocasematch is on. Leaving the option set globally would silently change matching in every later case and [[ in the script, which is why the block restores it immediately.

select builds a numbered menu loop

The select construct is a for-like loop that prints a numbered menu, reads a number from the user, and sets the loop variable to the chosen item. It pairs naturally with case to dispatch on the choice, and it loops until you break.

#!/usr/bin/env bash
PS3='choose an action: '
select action in start stop status quit; do
  case $action in
    start|stop|status) printf 'you picked: %s\n' "$action" ;;
    quit) printf 'exiting\n'; break ;;
    *) printf 'invalid choice: %s\n' "$REPLY" ;;
  esac
done

Driven with the inputs 1, 3, 9, then 4, the script produces this on standard output:

you picked: start
you picked: status
invalid choice: 9
exiting

Two details matter for using select in real scripts. First, the numbered menu and the PS3 prompt are written to standard error, not standard output, so the four lines above are the entire stdout; the menu itself does not pollute a redirected result. Second, an out-of-range entry such as 9 leaves action empty while REPLY still holds the raw 9, which is why the catch-all branch reports the invalid choice from REPLY. Without an explicit break, select loops forever, redisplaying the menu after each choice.


Real World Example: A Subcommand Dispatcher

Command-line tools with subcommands -- the start, stop, status shape of systemctl or git -- are the archetypal case application. The value being classified is the first argument, the patterns are the command words, and the catch-all handles the unknown-command error. This dispatcher also shows two techniques worth having: alternative patterns for aliases, and a branch that reuses others by calling the dispatcher again.

#!/usr/bin/env bash
# svc.sh -- a subcommand dispatcher built on case
set -u

usage() {
  printf 'usage: svc <command> [name]\n'
  printf '  commands: start | stop | restart | status | help\n'
}

dispatch() {
  local cmd=$1; shift
  local name=${1:-service}
  case $cmd in
    start)   printf '[start]   bringing up %s\n' "$name" ;;
    stop)    printf '[stop]    shutting down %s\n' "$name" ;;
    restart) dispatch stop "$name"; dispatch start "$name" ;;
    status)  printf '[status]  %s is running\n' "$name" ;;
    -h|--help|help) usage ;;
    '')      printf 'error: no command given\n' >&2; usage >&2; return 2 ;;
    *)       printf 'error: unknown command "%s"\n' "$cmd" >&2; return 127 ;;
  esac
}

for line in "start web" "status web" "restart web" "bogus" "help"; do
  read -r -a parts <<< "$line"
  dispatch "${parts[@]}"
  printf '  -> exit %d\n' "$?"
done

Output:

[start]   bringing up web
  -> exit 0
[status]  web is running
  -> exit 0
[stop]    shutting down web
[start]   bringing up web
  -> exit 0
error: unknown command "bogus"
  -> exit 127
usage: svc <command> [name]
  commands: start | stop | restart | status | help
  -> exit 0

Follow the dispatch. start web and status web each match one branch and return 0. restart web matches the restart branch, which calls dispatch twice more -- once for stop, once for start -- so three lines of output come from that one command, and its exit status is that of the last inner call, 0. The word bogus falls to the catch-all, which writes to standard error and returns 127, the conventional "command not found" code. The help alias branch -h|--help|help matches on any of the three spellings.

The dispatcher leans on the fact that case returns the status of the last command in the branch it ran, so the printf ' -> exit %d' after each call reads a meaningful code. Note the empty-string pattern '': because set -u is on and the loop always supplies a word, that branch is never reached here, but it is the correct guard for a real tool invoked with no argument, and it returns 2 to distinguish "you gave me nothing" from 127's "you gave me something I do not know".

The honest limits include one real design flaw. The catch-all returns 127, but the branch does not print the usage text the way a helpful tool should, so a user who mistypes a command gets an error on stderr and a bare exit code with no hint of the valid commands -- the help text exists but the error path does not point to it. A second, quieter issue is the restart branch: it runs stop then start unconditionally, ignoring whether stop succeeded, so a restart of a service that failed to stop would still attempt a start and report the start's status as though the whole restart worked. A production dispatcher would check the stop's status before starting, and would route unknown commands through usage before exiting.


Common Mistakes

  1. Ordering a broad pattern above a specific one. Because case stops at the first match, putting *.gz above *.tar.gz means every tarball is labelled a plain gzip file. Always arrange patterns from most specific to most general, exactly as the sorting frame puts its narrow slots at the top.
  1. Forgetting the catch-all * branch. A case with no *) simply does nothing when no pattern matches, and does so silently. Unless "do nothing" is genuinely intended, add a *) that reports the unexpected value, so an unhandled case is visible rather than a quiet no-op.
  1. Quoting the pattern and killing the glob. Writing "*.txt") as the pattern makes it a literal string containing an asterisk, so it only matches the exact name *.txt. Patterns on the left of ) are globs; leave them unquoted, and quote only the value in case "$x" in if you quote anything.
  1. Expecting ;; to fall through like C. A C switch falls through by default and needs break; case is the opposite -- ;; stops, and you must ask for fall-through with ;&. Porting a C switch verbatim either stops too early or, if you drop the terminators, is a syntax error.
  1. Leaving nocasematch set after you needed it. Because it is a global shell option, turning it on for one comparison and forgetting to turn it off changes matching for every later case and [[. Scope it tightly, setting it immediately before and unsetting it immediately after the block that needs it.
  1. Reading select output from standard output. The menu and PS3 prompt go to standard error, so a script that captures select with $( ) will not see the menu and may hang waiting for input. Use select for interactive prompts, not inside a command substitution.
  1. Omitting break in a select loop. select repeats until you break out of it, so a menu with no break on its quit branch loops forever. Every select needs an explicit exit path, usually a quit entry that runs break.
  1. Testing an out-of-range menu choice with the item variable. When the user types a number with no matching item, the loop variable is empty but REPLY holds the raw input. Check the empty item in the catch-all and report REPLY, rather than assuming the variable holds the invalid entry.
  1. Using a long if chain of string equality where case fits. A ladder of [ "$x" = "a" ] || [ "$x" = "b" ] comparisons is harder to read and to extend than one case with a|b) branches. When you are dispatching one value against many fixed shapes, case is the clearer instrument.

Best Practices

  • Order patterns from most specific to most general. The first-match rule means specificity must descend down the branch list. Put compound extensions and exact words at the top and the * catch-all at the bottom.
  • Always include a catch-all branch. A final *) that reports or handles the unexpected value turns a silent no-match into a visible event, which is what you want when a new input shows up that the other branches never anticipated.
  • Group aliases with the | alternation. Spellings like -h|--help|help or y|yes|Y|YES belong on one branch joined by |, which keeps related inputs together and the branch bodies free of repetition.
  • Reach for case over an if ladder when dispatching one value. Classifying a single value into many shapes reads far better as a case than as a chain of string comparisons, and it makes adding a new shape a one-line change.
  • Scope nocasematch to the smallest block. Set it right before the comparison that needs case-insensitivity and unset it right after, so the global toggle never leaks into unrelated matching later in the script.
  • Use ;& and ;;& sparingly and comment them. The non-default terminators are powerful but surprising to readers who expect every branch to stop. When you use fall-through, a short comment on why saves the next maintainer from assuming a bug.
  • Return meaningful exit codes from a dispatcher's branches. Let the catch-all return 127 for an unknown command and a distinct code for a missing one, so a calling script can tell the failure modes apart from the exit status alone.
  • Keep select for interaction and dispatch its result with case. The two pair cleanly: select gathers the choice and case acts on it. Keep a quit entry that breaks, and read invalid entries from REPLY.

Practice Exercises

  1. An extension router. Write a case-based function that takes a filename and prints the tool you would use to open it: an image viewer for *.png or *.jpg, an archive tool for *.zip, *.tar, or *.tar.gz, an editor for *.txt or *.md, and "no handler" otherwise. Order the patterns so *.tar.gz never falls to the plain *.tar branch, and test it on one name of each kind.
  1. Severity fall-through. Using ;&, write a case on a log level of debug, info, warn, or error such that each level performs its own action plus every action of the levels below it. Prove it by calling the function with warn and with error and showing that error produces strictly more output.
  1. A confirm prompt. Write a function that reads a yes/no answer and returns success only for an affirmative. Use case with nocasematch set locally so that y, yes, Y, and YES all count as yes, and anything else counts as no. Restore nocasematch afterward and confirm with a comment that later matching is unaffected.
  1. A menu-driven tool. Build a select menu offering "list files", "show date", "count lines in a file", and "quit". Dispatch each choice with a case, handle an invalid numeric entry by reporting REPLY, and break only on quit. Note in a comment why you would never capture this menu's output with command substitution.