Course contentsShow
← Linux
Lesson 156 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Complex Pattern Matching Blocks

Apply branching logic based on sophisticated textual analysis.

In this lesson, you will learn how to use case blocks to perform sophisticated branching logic based on flexible text patterns.

Moving Beyond Simple Equality

While if/else statements are perfect for binary decisions, they become clunky when you need to match a single input against multiple potential text patterns. In Bash, the case statement allows you to define a "pattern matching block" where one input is checked against several criteria, using wildcards and character classes to evaluate the string's structure.

The Anatomy of a Pattern Match

A case block starts with the case keyword and ends with esac. Inside, you define patterns followed by a closing parenthesis ), and the code to execute if that pattern matches. You terminate each branch with double semicolons ;;.

Consider a script that needs to categorize system logs based on their content:

log_entry="ERROR: Database connection failed"

case "$log_entry" in
    "DEBUG"*)
        echo "Processing a debug trace."
        ;;
    "ERROR"*)
        echo "Alert: Critical failure detected!"
        ;;
    *"failed" | *"timeout")
        echo "Connection issue identified."
        ;;
    *)
        echo "Unknown log type."
        ;;
esac

Why This is Powerful

  1. Globbing Integration: Unlike standard equality checks, case supports shell globs. The * acts as a wildcard, allowing you to match strings that start with or contain specific text.
  2. The OR Operator: By using the pipe symbol |, you can group multiple distinct patterns together. In the example above, the third branch triggers if the string ends in either "failed" or "timeout".
  3. The Catch-All: The * pattern acts as a "default" case. If none of your specific patterns match, the logic falls through to this branch, preventing your script from failing silently when it encounters unexpected input.

This approach is significantly cleaner and more readable than chaining multiple if [[ $var == *pattern* ]] statements. By organizing your logic into these blocks, you create a robust structure for analyzing streams of text or user input.

Key Takeaway: Use case blocks with wildcards and pipe delimiters to handle complex text branching cleanly and efficiently.