Regex matching with =~
[[ $text =~ $regex ]] checks whether text matches a POSIX extended regular expression (ERE). Unlike a shell glob, . matches one character and * repeats the preceding expression zero or more times; [0-9]+ matches one or more digits in the C locale. Use ^ and $ to anchor the start and end when the entire string must match. A match returns 0, no match 1, and an invalid regex 2. Store a trusted pattern in a variable and expand it unquoted on the right; quoting the whole pattern makes it literal. After success, BASH_REMATCH[0] holds the matched text and indices 1 onward hold parenthesized captures (array access preview; full arrays later). Read captures promptly and only after status 0 because another regex evaluation can change them. Status 2 indicates a malformed pattern, not an ordinary nonmatch; use an immediate status check when diagnosing a configurable pattern. Use validated, bounded numeric values before later arithmetic; digit validation alone does not guarantee range or decimal interpretation.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale. Output is shown separately; do not enter it as code.
Validate a fixed format
id=ID-42regex='^ID-[0-9]+$'if [[ $id =~ $regex ]]; then printf '%s\n' valid; fiExpected stdout:
validAnchors require the whole identifier to match.
Read captured groups
id=ID-42regex='^(ID)-([0-9]+)$'if [[ $id =~ $regex ]]; then printf '%s / %s / %s\n' "${BASH_REMATCH[0]}" "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"fiExpected stdout:
ID-42 / ID / 42Index zero is the full match; 1 and 2 are the captures.
Anchors and quoting
text=xID-42regex='^ID-[0-9]+$'[[ $text =~ $regex ]]; printf '%s\n' "$?"text=ID-42[[ $text =~ "$regex" ]]; printf '%s\n' "$?"Expected stdout:
11The extra prefix violates the anchored pattern; quoting the full regex also prevents its intended match.
Common mistakes
[0-9]+ without anchors can match part of an invalid identifier. Quoting the entire regex makes regex metacharacters literal. Check status before reading captures; do not assume old captures are still valid.
Practice
Use an anchored pattern to accept ID-42 and reject xID-42. Extract the digits from a valid identifier.
Next: case branches and patterns