Skip to content

Regex Tests

When working with BASH scripts, regular expressions (regex) are invaluable for pattern matching in conditional tests. BASH provides two primary mechanisms for this: the [[ ... ]] conditional test with the =~ operator and the grep command. Both allow you to validate strings, filter input, or check file contents against regex patterns. This section explores their usage in scripts.


Using Regex in [[ ... ]] Conditional Tests

The [[ ... ]] construct supports regex via the =~ operator, which evaluates whether a string matches a pattern. This is ideal for inline validation in scripts.

Basic Syntax

if [[ "$variable" =~ regex_pattern ]]; then
    # Match logic
fi

Example 1: Check if a User is Root

if [[ "$USER" =~ ^root$ ]]; then
    echo "User is root"
fi

Example 2: Validate an Email Address

if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
    echo "Valid email format"
else
    echo "Invalid email format"
fi

Notes

  • Regex is Perl-compatible in [[ ... ]], supporting features like ^ (start of string), $ (end of string), and character classes.
  • Always quote variables to prevent globbing or unintended expansion:
    if [[ "$var" =~ ^pattern$ ]]; then ...
    

Using Regex with grep

The grep command filters lines matching a regex. It’s useful for searching files or standard input.

Basic Syntax

grep 'pattern' file.txt

Example 1: Match Phone Numbers

grep -E '^[0-9]{3}-[0-9]{3}-[0-9]{4}$' phone_list.txt
- -E enables extended regex (e.g., ^ and $ for line boundaries).

grep -i 'error' log.txt
- -i ignores case distinctions.

Example 3: Match Multiple Patterns

grep -E 'error|warning' log.txt
- -E allows multiple patterns separated by |.


Key Takeaways

  • Use [[ ... ]] with =~ for inline regex validation in conditionals.
  • Use grep with -E for line-based pattern matching in files or streams.
  • Always quote variables in [[ ... ]] to avoid globbing.
  • Be mindful of case sensitivity and escape special characters when needed.