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 value in
pattern1) commands1 ;;
pattern2) commands2 ;;
...
*) default_commands ;;
esac
PARAMETERS
value
The variable or expression to be evaluated.
pattern
A pattern to match against the value. Can include literals, wildcards (*, ?, []), or alternation (|).
commands
The commands to execute if the corresponding pattern matches the value.;;
Terminates the command list for a specific pattern, preventing fallthrough to the next pattern.*)
A wildcard pattern that matches any value not matched by the previous patterns. It defines the default case.
DESCRIPTION
The case
command in Linux is a control flow statement that allows you to execute different commands based on the value of a variable or expression. It provides a more readable and structured alternative to nested if
-then
-else
statements when dealing with multiple conditions. The case
command works by comparing a specified value against a series of patterns. When a pattern matches the value, the corresponding commands are executed. The case
statement ends with the esac
keyword (case reversed). The patterns can include literal values, wildcard characters (*, ?, []), and alternation (|). It is commonly used in shell scripts to handle different input options, system states, or user choices. The case
statement offers improved script readability and maintainability by organizing conditional logic in a clear and concise manner.
CAVEATS
If multiple patterns match the value, only the commands associated with the first matching pattern are executed. It's important to order patterns carefully to avoid unintended behavior.
WILDCARDS AND REGULAR EXPRESSIONS
While the case
statement supports wildcards, it's important to note they are not regular expressions. The '*' matches zero or more characters, '?' matches any single character, and '[]' defines a character class. For more complex pattern matching, consider using tools like grep
or regular expression constructs within the shell.
EXIT STATUS
The exit status of the case
statement is the exit status of the last command executed within the matching pattern. If no pattern matches, the exit status is 0.
HISTORY
The case
statement is a fundamental part of the Bourne shell and its descendants (Bash, Zsh, etc.). It has been a standard feature of Unix-like operating systems since the early days of shell scripting, providing a structured way to handle multiple conditional branches.