case
Execute code based on pattern matching
TLDR
Match a variable against string literals to decide which command to run
Combine patterns with |, use * as a fallback pattern
Allow matching multiple patterns
Continue to the next pattern's commands without checking the pattern
Display help
SYNOPSIS
case word in
[[(]pattern[ | pattern ]... ) command-list ;; ]... esac
DESCRIPTION
The case statement is a core control structure in POSIX-compliant shells like Bash, providing multi-way branching based on pattern matching. It evaluates a word (typically a variable) against a list of patterns, executing the first matching block of commands. Patterns support shell glob characters (*, ?, [...]) and can be OR'd with |.
Unlike nested if-elif, case is more readable for many discrete values. Each case ends with ;;; a default *) case handles unmatched. The structure reverses to esac. No fall-through occurs; matching stops at first hit.
Used extensively in scripts for argument parsing, e.g., handling command-line options or file extensions. Expansions on word and patterns follow shell rules, but matching uses fnmatch without pathname expansion.
CAVEATS
No fall-through between cases; use ;& or ;;& in Bash 4+ for continuable cases. Patterns match literally after expansion, no regex. Long command-lists may need { ...; } for grouping.
BASIC EXAMPLE
case $1 in
start) start_service ;;
stop) stop_service ;;
*) echo "Usage: $0 {start|stop}" ;;
esac
EXIT STATUS
Exits with the status of the last command executed in the selected case, or zero if none matched and no default case.
HISTORY
Originated in Bourne shell (1977, Version 7 Unix). Standardized in POSIX.1-1988. Bash enhanced with ;;& (4.0, 2009) and ;& for partial matches.


