0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Regex in Bash: Syntax, Examples, and Tips

In bash, you can use regex with the [[ string =~ regex ]] conditional expression to test if a string matches a pattern. The regex must be unquoted and follows extended regular expression syntax. Use this inside if statements or loops to automate pattern matching.
📐

Syntax

The basic syntax to use regex in bash is:

  • [[ string =~ regex ]]: Tests if string matches the regex.
  • The regex is an extended regular expression and should not be quoted.
  • If the match succeeds, the condition returns true (exit status 0).
  • You can access matched groups using BASH_REMATCH array.
bash
[[ string =~ regex ]]

# Example:
if [[ "hello123" =~ [a-z]+[0-9]+ ]]; then
  echo "Match found"
fi
💻

Example

This example checks if a variable contains a word followed by digits and prints the matched parts.

bash
#!/bin/bash
input="user42data"
if [[ $input =~ ([a-z]+)([0-9]+) ]]; then
  echo "Full match: ${BASH_REMATCH[0]}"
  echo "Letters: ${BASH_REMATCH[1]}"
  echo "Numbers: ${BASH_REMATCH[2]}"
else
  echo "No match"
fi
Output
Full match: user42 Letters: user Numbers: 42
⚠️

Common Pitfalls

Common mistakes when using regex in bash include:

  • Quoting the regex pattern, which disables regex matching.
  • Using single brackets [ ] instead of double brackets [[ ]] for regex tests.
  • Expecting regex to behave like grep or sed without understanding bash's regex flavor.

Here is a wrong and right example:

bash
# Wrong: regex pattern quoted disables matching
input="abc123"
if [[ "$input" =~ "[a-z]+[0-9]+" ]]; then
  echo "Matched"
else
  echo "No match"
fi

# Right: regex unquoted
if [[ "$input" =~ [a-z]+[0-9]+ ]]; then
  echo "Matched"
else
  echo "No match"
fi
Output
No match Matched
📊

Quick Reference

ConceptDescriptionExample
Regex testCheck if string matches regex[[ $str =~ regex ]]
Access groupsGet matched groups from regexBASH_REMATCH[1], BASH_REMATCH[2]
No quotesDo not quote regex pattern[[ $str =~ [a-z]+ ]]
Double bracketsUse [[ ]] for regex, not [ ][[ $str =~ regex ]]
Exit status0 if match, 1 if no matchif [[ $str =~ regex ]]; then ... fi

Key Takeaways

Use double brackets [[ ]] with =~ operator for regex matching in bash.
Do not quote the regex pattern; it must be unquoted for proper matching.
Access captured groups with the BASH_REMATCH array after a successful match.
Remember regex matching returns exit status 0 on success, 1 on failure.
Avoid using single brackets [ ] or quoting regex to prevent matching errors.