Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 95 ยท Shell Scripting

case Statements and Menus

Master the Bash case statement: glob patterns, multiple alternatives, ;; ;& ;;& terminators, parsing options, and building select menus. Learn case versus if.

Sooner or later a script has to look at one value and do a different thing depending on what it is: a command name (start, stop, restart), a file extension, an option flag, a yes/no answer. You could write a long ladder of if and elif tests, but the shell has a purpose-built tool for this shape of problem: the case statement. It is shorter, easier to read, and it matches patterns, not just exact strings.

In this lesson you will learn the case syntax, how its glob-style patterns work, the three ways to end a branch (;;, ;&, ;;&), the standard way to parse command-line options, and how select builds a numbered menu. You will also learn when case is the right choice and when if is better.

The shape of case

TEXT
   case WORD in
     PATTERN1)            commands ;;
     PATTERN2 | PATTERN3) commands ;;
     *)                   commands ;;      <- default: matches anything
   esac                                    <- "case" backwards

Bash expands WORD once, then compares it with each pattern from top to bottom. The first pattern that matches wins: its commands run, and (with ;;) the statement is finished. Patterns are globs, like file-name wildcards (Wildcards and Globbing), not regular expressions. A | separates alternatives. The closing parenthesis ) after the pattern is required; an optional opening ( is allowed too.

Bash A command dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Notes on this output:

  • stop|halt matches either word.
  • The empty string needs its own pattern, "".
  • Start does not match start: patterns are case-sensitive by default. We return to that below.
  • "two words" reaches the default *) pattern. Because case does not word-split its subject, you do not need to quote $1 in case $1 in. Quoting the patterns matters when you want a literal match ("*" means a star character).
  • Always put a *) default branch last, even if it only prints an error. It is the else of the statement. Without it, an unexpected value silently does nothing.

Patterns in depth

Everything you know about globbing works here: * (any string, including empty), ? (exactly one character), [abc], [0-9], [!a], and POSIX classes like [[:upper:]]. Because the first match wins, order matters: put specific patterns before general ones.

Bash Glob patterns, nocasematch and extglob

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Observe:

  • A name is checked against each pattern in order. Readme is not a digit start and not one character, so it reaches [[:upper:]]*.
  • shopt -s nocasematch makes case (and [[ ]]) ignore letter case, which is handy for accepting Y, y, YES and yes with one pattern. Switch it off again afterwards, because it is a global setting.
  • shopt -s extglob enables extended patterns: @(a|b) (one of), ?(a|b) (zero or one), *(a|b) (zero or more), +(a|b) (one or more) and !(a|b) (anything except). In scripts, turn it on before the case statement that uses it, because Bash parses a whole compound command before running it.
  • The same value can match several patterns, but only the first one runs. The last example prints first only.

Ending a branch: ;; ;& and ;;&

The ;; at the end of each branch means "done, leave the case". Bash 4 added two more terminators:

Terminator After running this branch...
;; stop (the normal case)
;& fall through: run the next branch's commands without testing its pattern
;;& keep testing: continue with the next patterns, and run any that also match
Bash Fall through and keep testing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Reading the results:

  • With ;&, matching b also ran c's commands but not d's. Fall-through is the opposite of C's default and is rarely needed.
  • With ;;&, the word abc matched a*, *c and *b*, in that order, so three lines were printed. The * default was not reached because the last matching branch used ;;.
  • If nothing matches, case returns status 0. Otherwise its status is that of the last command it ran (here false, so 1). Do not rely on case to "fail" when nothing matches, add a *) branch that returns an error.
  • case is a compound command, so its output can be captured with $( ) as in the last lines. The final branch before esac does not strictly need ;;, but add it for consistency.

Bash 3.2, still the default on macOS, does not know ;& and ;;&. They also do not exist in POSIX sh. Use plain ;; in scripts that must run everywhere, see POSIX sh, Portability and Compatibility.

Parsing options with case

The single most common use of case in real scripts is a loop that walks through the command-line arguments and sets variables. The pattern is: test $1, handle it, shift to remove it, and repeat until none are left.

Bash An option-parsing loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

How the loop works:

  1. While there are arguments left ($# -gt 0), look at the first one.
  2. A flag like -v sets a variable. An option with a value (-n Ann) reads the value from $2 and does an extra shift to consume it.
  3. --name=Bob is the "equals" spelling, handled by cutting off the prefix with ${1#--name=} (Parameter Expansion and String Handling).
  4. -- is the conventional "end of options" marker. Everything after it is data, even if it starts with a dash (the file named -file).
  5. Any other word starting with - is an unknown option: report it on stderr and return status 2 (the convention for usage errors).
  6. A word that does not start with a dash is the first positional argument, so stop parsing and leave the rest in $@.

The built-in getopts and a fuller template are covered in Script Arguments and Options. A case loop is the better tool when you want long options.

select is a Bash loop that prints a numbered menu from a list, reads a number from the user, sets a variable to the matching item, and runs the body. It repeats until you break (or until end of input). The prompt text comes from the variable PS3; the menu itself and the prompt are written to stderr, and the raw text the user typed is stored in REPLY.

TEXT
   select VAR in item1 item2 item3; do
       ...            <- VAR is set to the chosen item, REPLY holds what was typed
   done

select is interactive, so on a real terminal it waits for you to type. In our editor you drive it through the Input box: each line there acts as one answer. The next example is preset with the answers 2, 9, 1 and 4.

Bash A select menu driven by preset input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The output shows you picked banana (item 2), then invalid choice: 9 (a number outside the menu leaves fruit empty, so the "" branch handles it), then you picked apple (item 1), then bye for the fourth entry, and finally done. The menu itself (1) apple, 2) banana, ...) and the repeated prompts appear in the error stream, below the normal output.

Notes about select:

  • It is a natural partner of case, as above: the loop handles input, case handles the choices.
  • It does not stop on its own. Always offer a "quit" entry or break on end of input; otherwise the menu repeats until the input ends.
  • Menus are a poor fit for scripts that run unattended or in pipelines, since they need a person (or piped answers). For simple prompts, read is more flexible, see Reading Input and Interactive Scripts.

case or if?

Use case when one value is compared against several patterns: commands, extensions, option names, answers like y|Y|yes. The structure is flat and each branch is easy to find.

Use if/[[ ]] when the conditions are different tests (a file check here, a number comparison there), when you need regular expressions (=~), or when two or three conditions are combined. case can only match one string against globs; it cannot combine tests such as "is a file and is bigger than 1 MB". See Conditionals: if, test and [[ ]].

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In case $x in a*) echo 1 ;; *b) echo 2 ;; esac, what is printed when x is ab?

    Both patterns match, but the first matching pattern wins and ;; ends the case statement, so only 1 is printed.
  2. 2. What kind of patterns does case use?

    case matches shell glob patterns: *, ?, [..] and (with extglob) @(..) and similar. Use [[ =~ ]] when you need regular expressions.
  3. 3. What does the ;& terminator do?

    ;& falls through into the next branch. ;;& is the one that keeps testing the remaining patterns.
  4. 4. What exit status does case return when no pattern matches and there is no *) branch?

    An unmatched case returns 0, so you cannot detect a missing match from the status. Add a default *) branch that reports the problem.
  5. 5. In a select loop, where do the numbered menu and the PS3 prompt go, and where is the raw text the user typed stored?

    select writes the menu and the prompt to standard error and stores whatever was typed in REPLY. The chosen item goes into the loop variable (empty for an invalid number).

Summary

  • case WORD in PATTERN) commands ;; ... esac runs the first branch whose glob pattern matches; a|b gives alternatives and *) is the default.
  • Patterns are globs, case-sensitive by default; shopt -s nocasematch ignores case and shopt -s extglob adds @() ?() *() +() !().
  • ;; ends the statement, ;& falls through, ;;& keeps testing (Bash 4+). An unmatched case returns status 0.
  • The classic option parser is while [[ $# -gt 0 ]]; do case $1 in ... esac; shift; done, with -- for end of options.
  • select builds a numbered menu from a list; menu and prompt go to stderr, PS3 sets the prompt, REPLY holds the typed text, and you must break out.
  • Choose case for one value against many patterns, if for mixed or combined tests.

Next: Loops: for, while and until