Pattern Matching with case Statements

Updated

October 31, 2026

Pattern Matching with case Statements

The case statement provides high-performance pattern matching without invoking subshells:

case "$os_type" in
    ubuntu|debian)
        pkg_mgr="apt-get"
        ;;
    fedora|rhel|centos)
        pkg_mgr="dnf"
        ;;
    alpine)
        pkg_mgr="apk"
        ;;
    arch)
        pkg_mgr="pacman"
        ;;
    *)
        echo "Unsupported distribution: $os_type" >&2
        exit 1
        ;;
esac

Advanced Terminators in Bash

  • ;;: Terminates execution (standard).
  • ;&: Fall-through to the next clause without testing its pattern.
  • ;;&: Tests subsequent patterns and executes if matched.