case branches and patterns
case word in pattern) commands ;; ... esac selects a branch using shell patterns, not regular expressions. Patterns are tried in order; ;; finishes the case after a match. Use pattern1|pattern2) for alternatives, and put *) last as a default. In Bash, ;& runs the next clause body without checking its pattern, while ;;& resumes testing later patterns. These two forms are Bash extensions and are not needed for ordinary branching. If no clause matches, case returns status zero; otherwise its status is that of the last command run. The ordinary ;; form is suitable for portable shell scripts.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale. Output is shown separately; do not enter it as code.
Choose an action
action=startcase $action in start|restart) printf '%s\n' launching ;; stop) printf '%s\n' stopping ;; *) printf '%s\n' unknown ;;esacExpected stdout:
launchingThe first clause accepts either of two words.
Classify a filename
name=notes.mdcase $name in *.txt|*.md) printf '%s\n' document ;; *.csv) printf '%s\n' table ;; *) printf '%s\n' other ;;esacExpected stdout:
documentA glob pattern classifies the string without inspecting the file.
Compare terminators
case apple in a*) printf '%s\n' first ;;& z*) printf '%s\n' skipped ;; *e) printf '%s\n' second ;& z*) printf '%s\n' forced ;;esacExpected stdout:
firstsecondforced;;& checks the next patterns; ;& executes the next body regardless of its pattern.
Common mistakes
Putting *) first catches everything under normal ;; termination. Do not accidentally use ;& if only one branch should run.
Practice
Classify start, stop, and unknown commands using a case statement with a default branch. Then classify notes.md and data.csv by extension.
Next: Arithmetic