LinuxCommandLibrary

case

Execute code based on pattern matching

TLDR

Match a variable against string literals to decide which command to run

$ case [$COUNTRULE] in [words]) [wc --words README] ;; [lines]) [wc --lines README] ;; esac
copy

Combine patterns with |, use * as a fallback pattern
$ case [$COUNTRULE] in [[wW]|words]) [wc --words README] ;; [[lL]|lines]) [wc --lines README] ;; *) [echo "what?"] ;; esac
copy

Allow matching multiple patterns
$ case [$ANIMAL] in [cat]) [echo "It's a cat"] ;;& [cat|dog]) [echo "It's a cat or a dog"] ;;& *) [echo "Fallback"] ;; esac
copy

Continue to the next pattern's commands without checking the pattern
$ case [$ANIMAL] in [cat]) [echo "It's a cat"] ;& [dog]) [echo "It's either a dog or cat fell through"] ;& *) [echo "Fallback"] ;; esac
copy

Display help
$ help case
copy

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.

SEE ALSO

bash(1), dash(1), ksh(1)

Copied to clipboard