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¶
Example 1: Check if a User is Root¶
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:
Using Regex with grep¶
The grep command filters lines matching a regex. It’s useful for searching files or standard input.
Basic Syntax¶
Example 1: Match Phone Numbers¶
--E enables extended regex (e.g., ^ and $ for line boundaries).
Example 2: Case-Insensitive Search¶
--i ignores case distinctions.
Example 3: Match Multiple Patterns¶
--E allows multiple patterns separated by |.
Key Takeaways¶
- Use
[[ ... ]]with=~for inline regex validation in conditionals. - Use
grepwith-Efor 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.