Case Statements

Multi-way branching based on pattern matching

Basic case statement

Simple case statement with options

#!/bin/bash
case $1 in
    "start")
        echo "Starting service"
        ;;
    "stop")
        echo "Stopping service"
        ;;
    "restart")
        echo "Restarting service"
        ;;
    *)
        echo "Unknown command"
        ;;
esac
Case with pattern matching

Case with wildcard patterns

#!/bin/bash
case $filename in
    *.txt)
        echo "Text file"
        ;;
    *.jpg|*.png|*.gif)
        echo "Image file"
        ;;
    *)
        echo "Unknown file type"
        ;;
esac
Case with regex patterns

Case statement with character class patterns

#!/bin/bash
case $input in
    [0-9]*)
        echo "Starts with digit"
        ;;
    [a-zA-Z]*)
        echo "Starts with letter"
        ;;
    *)
        echo "Other pattern"
        ;;
esac
Case with multiple patterns

Case statement with multiple pattern matching

#!/bin/bash
case $file in
    *.txt|*.log)
        echo "Text file"
        ;;
    *.jpg|*.png|*.gif)
        echo "Image file"
        ;;
    *.mp3|*.wav)
        echo "Audio file"
        ;;
    *)
        echo "Unknown file type"
        ;;
esac
Case with range patterns

Case statement with numeric range patterns

#!/bin/bash
case $number in
    [1-5])
        echo "Low number"
        ;;
    [6-9])
        echo "Medium number"
        ;;
    1[0-9])
        echo "High number"
        ;;
    *)
        echo "Out of range"
        ;;
esac
Bash case with character classes

Bash case statement with character class patterns

#!/bin/bash
input="A123"
case $input in
    [A-Z]*)
        echo "Starts with uppercase letter"
        ;;
    [a-z]*)
        echo "Starts with lowercase letter"
        ;;
    [0-9]*)
        echo "Starts with digit"
        ;;
    *)
        echo "Other pattern"
        ;;
esac