Shell Script · Case Statement

Shell Scripting · Lesson 13

Case Statement

Implement menu driven scripts using case statement. Pattern matching in bash. Replace multiple if conditions. Professional script design.

What is a Case Statement?

A case statement allows you to execute different blocks of code based on the value of a variable.

It is often used as an alternative to long if-elif-else chains.

Why Use Case Statement?

Readable

Cleaner and easier to read than multiple if-else conditions.

Efficient

Simplifies decision-making logic.

Pattern Matching

Supports pattern-based matching.

Case Statement Syntax

case syntax
syntax
case $variable in
pattern1)
commands
;;
pattern2)
commands
;;
*)
default commands
;;
esac

Case Statement Examples

1. Basic Case Statement

Simple case statement to match a single value.

terminal — bash
case
read -p "Enter a number (1-3): " num
 
case $num in
1)
echo "You selected One"
;;
2)
echo "You selected Two"
;;
3)
echo "You selected Three"
;;
*)
echo "Invalid option"
;;
esac

2. Menu Driven Program

A real-world example using case for menu selection.

terminal — bash
case
echo "1. Start"
echo "2. Stop"
echo "3. Restart"
 
read -p "Choose an option: " choice
 
case $choice in
1)
echo "Service Started"
;;
2)
echo "Service Stopped"
;;
3)
echo "Service Restarted"
;;
*)
echo "Invalid Option"
;;
esac

3. Pattern Matching in Case

Case statement can match patterns.

terminal — bash
case
read -p "Enter a character: " ch
 
case $ch in
[a-z])
echo "Lowercase letter"
;;
[A-Z])
echo "Uppercase letter"
;;
[0-9])
echo "Digit"
;;
*)
echo "Special character"
;;
esac

Best Practices

Recommended Usage

  • Always include a default (*) case.
  • Use clear and readable patterns.
  • Avoid overly complex case blocks.
  • Use case for menus and user choices.

Practice Task – Case Statement

  • Create a menu-driven calculator.
  • Build a menu to start/stop a service.
  • Use case to check file types.

Next lesson: Functions in Shell Scripting