Case statement in bash

Bash, the beloved scripting language for Linux and Unix systems, offers a powerful tool for decision-making: the case statement. Let’s unravel how this feature can elevate your scripts’ efficiency and readability.

What is a Bash Case Statement?

Think of a case statement as an elegant way to compare a variable’s value against multiple possibilities. It’s like having a series of “if-else” checks, but much neater.

How It Works

  • Expression: The variable you want to evaluate.
  • Patterns: A list of potential values the variable might hold. These patterns often resemble file globbing patterns (think *.txt).
  • Statements: The actions to execute if a pattern matches the expression.

Syntax Breakdown

case "$variable" in
    statements ;;
    statements ;;
    statements ;; # Default case (catch-all)

Important Notes:

  • Order Matters: Patterns are checked in sequence, so put your most specific matches first.
  • Double Semicolons: These ;; signify the end of statements for each pattern.
  • Wildcards: The * acts as a wildcard, matching any sequence of characters.


Example 1: Yes or No Response

read -p "Are you sure? (yes/no) " ans

case "$ans" in
    echo "Will do!" ;;
    echo "Oops!" ;;
    echo "Invalid input. Please enter yes or no." ;;

Example 2: File Type Identifier


case "$filename" in
    echo "Text file" ;;
    echo "Image file" ;;
    echo "Unknown file type" ;;


Text file

Example 3: Numeric Comparison


case "$number" in
    echo "Small number" ;;
    echo "Bingo! It's five!" ;;
    echo "Larger number" ;;
    echo "Not a number between 0 and 9" ;;


Bingo! It's five!

Why Use Case Statements?

  • Enhanced Readability: Compared to a long string of if-else statements, case is more organized and visually appealing.
  • Efficient Logic: When dealing with multiple options, case statements often execute faster.

Leave a Reply

Your email address will not be published. Required fields are marked *