The case statement in Linux (specifically in bash scripting) is a control flow statement that allows pattern-based branching. It is similar to a switch statement in other programming languages and is used to simplify conditional structures when comparing a variable against multiple values or patterns.
case variable in
pattern1)
commands
;;
pattern2)
commands
;;
*)
commands
;;
esacvariable: The variable or value being tested.pattern: A value or a wildcard pattern to match against the variable.commands: The commands to execute if thevariablematches the pattern.;;: Marks the end of the commands for a pattern.*: A wildcard pattern that matches anything (default case).esac: Ends thecasestatement.
#!/bin/bash
echo "Enter a choice: start, stop, or restart"
read action
case $action in
start)
echo "Starting the service..."
;;
stop)
echo "Stopping the service..."
;;
restart)
echo "Restarting the service..."
;;
*)
echo "Invalid choice!"
;;
esac- Input
start→ OutputsStarting the service... - Input
invalid→ OutputsInvalid choice!
The case statement supports patterns, including wildcards.
#!/bin/bash
read -p "Enter a file extension (e.g., .sh, .txt, .jpg): " ext
case $ext in
*.sh)
echo "This is a shell script file."
;;
*.txt)
echo "This is a text file."
;;
*.jpg|*.png)
echo "This is an image file."
;;
*)
echo "Unknown file type."
;;
esacYou can use the | operator to combine multiple patterns.
#!/bin/bash
read -p "Enter a day of the week: " day
case $day in
Monday|Tuesday|Wednesday|Thursday|Friday)
echo "It's a weekday."
;;
Saturday|Sunday)
echo "It's the weekend!"
;;
*)
echo "That's not a valid day."
;;
esacCase statements can also handle numerical patterns.
#!/bin/bash
read -p "Enter a number (1-10): " num
case $num in
[1-3])
echo "You entered a number between 1 and 3."
;;
[4-6])
echo "You entered a number between 4 and 6."
;;
[7-9]|10)
echo "You entered a number between 7 and 10."
;;
*)
echo "Invalid number."
;;
esacThe * wildcard is used as the default case when none of the specified patterns match.
#!/bin/bash
read -p "Enter a command (start/stop/restart): " cmd
case $cmd in
start)
echo "Service starting..."
;;
stop)
echo "Service stopping..."
;;
restart)
echo "Service restarting..."
;;
*)
echo "Command not recognized."
;;
esac- Readable: Simplifies complex if-else chains.
- Efficient: Matches patterns directly without multiple condition evaluations.
- Flexible: Allows wildcards, ranges, and multiple patterns.
- Patterns must end with a
)character. - Each pattern can include multiple matching criteria separated by
|. - Always end a
caseblock with;;for each pattern. - Use
*as the default case to handle unexpected input.
By using case, you can create cleaner and more maintainable scripts for handling user input or managing different conditions in Linux.