Bash Pattern Matching: Globbing, Extended Globs, and Regex =~ Guide
Learn bash pattern matching with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn bash pattern matching with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What bash Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Mastering bash pattern matching enables developers and system administrators to validate user input, parse complex strings, filter filesystem paths, and control execution flow natively without the overhead of spawning external binaries like grep, sed, or awk. Implemented directly in GNU Bash, pattern matching ranges from basic shell wildcards to full POSIX Extended Regular Expressions.
Bash pattern matching encompasses pathname globbing (*, ?), extended globs via shopt -s extglob, and regular expression evaluation using the [[ $str =~ $regex ]] operator. Run [[ $input =~ ^[0-9]+$ ]] to validate numeric input, and extract captured regex groups directly from the BASH_REMATCH array.
A defining feature of modern Bash (version 3.0+) is the binary regex evaluation operator (=~), available within the double-bracket compound condition [[ ... ]]. When evaluated, Bash compiles the regular expression using the system's POSIX regex library, tests the target string, and automatically populates the BASH_REMATCH array with the complete match and all captured subexpressions.
Combined with extended globbing (shopt -s extglob) and parameter expansions (${var#pattern}, ${var%pattern}, ${var//pattern/replace}), native pattern matching transforms Bash into an immensely capable text-parsing runtime that executes at native shell speeds.
What bash Does and When to Use It
At the architectural level, Bash implements pattern matching through two distinct internal subsystems: the glob matching engine based on fnmatch(3) and the regular expression compiler based on the standard POSIX regcomp(3) and regexec(3) APIs. When you enable extended globs via shopt -s extglob, Bash's parser activates composite matching constructs: ?(pattern) (zero or one), *(pattern) (zero or more), +(pattern) (one or more), @(pattern) (exactly one), and !(pattern) (anything except).
When the =~ operator is evaluated inside [[ string =~ regex ]], Bash passes the unquoted right-hand operand to regcomp(3) with flags REG_EXTENDED. If the compilation succeeds, it invokes regexec(3) with REG_STARTEND to execute the match. If the expression matches, Bash dynamically creates and populates the internal BASH_REMATCH read-only array: index 0 holds the entire substring matched by the pattern, while indices 1 through $N$ hold the specific substrings matched by corresponding parenthesized capture groups.
Under the hood, bash gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as =~, BASH_REMATCH, shopt -s extglob, shopt -s nocasematch turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The bash utility is packaged in bash across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether bash is installed and inspect which binary path and version your shell resolves:
type -a bash
bash --version 2>/dev/null || man -f bash
# Illustrative output (reviewed against documentation)
bash is /usr/bin/bash
bash (bash)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y bash
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y bash
# Arch Linux
sudo pacman -S --noconfirm bash
# Alpine Linux
sudo apk add --no-cache bash
Command Syntax, Arguments, and Exit Status Codes
[[ STRING =~ REGEX ]] | shopt -s extglob
The conditional regex syntax is [[ STRING =~ REGEX ]]. Crucially, in Bash 3.2 and later, the REGEX operand must NOT be enclosed in quotes if you intend metacharacters to be treated as regular expression operators. Quoting any part of the regex forces Bash to treat those characters as literal strings.
Best practice is to assign complex regular expressions to a dedicated shell variable first (e.g. REGEX='^[a-z]+[0-9]+$') and then evaluate with [[ $VAR =~ $REGEX ]]. This completely avoids shell quoting and escaping ambiguities across differing Bash subversions.
0— The pattern or regular expression matched the target string.1— The pattern or regular expression did NOT match the target string.2— Regular expression syntax error or malformed expression.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
=~ | =~ | Binary operator inside [[ ... ]] evaluating regular expression matching. |
BASH_REMATCH | BASH_REMATCH | Array variable holding the complete match (${BASH_REMATCH[0]}) and capture groups. |
shopt -s extglob | shopt -s extglob | Enable extended globbing patterns: ?(), *(), +(), @(), !(). |
shopt -s nocasematch | shopt -s nocasematch | Enable case-insensitive matching for [[ ... ]], case statements, and globs. |
shopt -s globstar | shopt -s globstar | Enable recursive directory globbing using **. |
shopt -s nullglob | shopt -s nullglob | Patterns that match no files expand to nothing rather than the literal pattern string. |
The quoting rule for =~ is the single most common pitfall in Bash scripting. If you write [[ $ip =~ "^[0-9]+$" ]], Bash treats ^, +, and $ as literal characters, causing the test to fail on valid numbers. Writing [[ $ip =~ ^[0-9]+$ ]] or storing the regex in an unquoted variable solves this cleanly.
Enabling shopt -s nocasematch allows writing case-insensitive validations without littering regular expressions with [a-zA-Z]. Running shopt -s nocasematch affects all conditional [[ ... ]] string comparisons, case statement matching, and pathname globbing.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Validate Numeric Input with the =~ Regex Operator
Verify that a user-supplied variable consists strictly of digits.
PORT="8080"
if [[ "$PORT" =~ ^[0-9]+$ ]]; then
echo "Valid port number: $PORT"
else
echo "Invalid port: must be numeric"
fi
# Illustrative output (reviewed against documentation)
Valid port number: 8080
The regex ^[0-9]+$ anchors the match from start to end, verifying every character is a digit.
2. Extract Regex Capture Groups Using BASH_REMATCH
Parse a semantic version string and extract major, minor, and patch numbers.
VERSION="v2.14.8"
REGEX='^v([0-9]+).([0-9]+).([0-9]+)$'
if [[ "$VERSION" =~ $REGEX ]]; then
echo "Full Match: ${BASH_REMATCH[0]}"
echo "Major: ${BASH_REMATCH[1]}"
echo "Minor: ${BASH_REMATCH[2]}"
echo "Patch: ${BASH_REMATCH[3]}"
fi
# Illustrative output (reviewed against documentation)
Full Match: v2.14.8
Major: 2
Minor: 14
Patch: 8
Parentheses in the regex define capture groups, which Bash stores sequentially in indices 1, 2, and 3 of BASH_REMATCH.
3. Validate IPv4 Addresses with Regex
Check if a string conforms to the dotted-quad format of an IPv4 address.
IP="192.168.1.50"
IP_REGEX='^([0-9]{1,3}.){3}[0-9]{1,3}$'
if [[ "$IP" =~ $IP_REGEX ]]; then
echo "Valid IPv4 format: $IP"
fi
# Illustrative output (reviewed against documentation)
Valid IPv4 format: 192.168.1.50
The regular expression validates four numeric segments separated by dots.
4. Match File Patterns Using Extended Globbing (extglob)
Match and remove files that do NOT match specific extensions using !().
shopt -s extglob
touch test.jpg test.png test.txt test.bak
# List all files EXCEPT .jpg and .png:
ls -1 !(*.jpg|*.png)
rm -f test.jpg test.png test.txt test.bak
# Illustrative output (reviewed against documentation)
test.bak
test.txt
The extended glob pattern !(*.jpg|*.png) matches any file whose name does not end in .jpg or .png.
5. Case-Insensitive String Matching with nocasematch
Accept user confirmation in any case variation (yes, Yes, YES) cleanly.
shopt -s nocasematch
RESPONSE="yEs"
if [[ "$RESPONSE" =~ ^(yes|y)$ ]]; then
echo "Action confirmed."
fi
shopt -u nocasematch
# Illustrative output (reviewed against documentation)
Action confirmed.
Enabling nocasematch allows case-insensitive matching across regex conditions and case statements.
6. String Extraction Using Parameter Expansion Pattern Slicing
Extract directory and file extensions natively without calling basename or dirname.
FILEPATH="/var/log/nginx/access.log.gz"
FILENAME="${FILEPATH##*/}"
EXTENSION="${FILEPATH##*.}"
DIRNAME="${FILEPATH%/*}"
echo "Filename: $FILENAME"
echo "Extension: $EXTENSION"
echo "Directory: $DIRNAME"
# Illustrative output (reviewed against documentation)
Filename: access.log.gz
Extension: gz
Directory: /var/log/nginx
Bash parameter pattern matching (${var##pattern} and ${var%pattern}) strips prefixes and suffixes at zero process cost.
Real-World Workflows, Pipelines, and Shell Automation
Production Input Sanitizer: CLI Argument Validation Framework
Validate complex configuration inputs (URLs, emails, UUIDs) natively in deployment scripts.
#!/usr/bin/env bash
set -euo pipefail
validate_email() {
local email="$1"
local email_regex='^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$'
if [[ "$email" =~ $email_regex ]]; then
return 0
else
return 1
fi
}
TEST_EMAILS=("[email protected]" "invalid-email@" "[email protected]")
echo "=== Auditing Email Formats via Bash Regex ==="
for e in "${TEST_EMAILS[@]}"; do
if validate_email "$e"; then
printf "[VALID] %s\n" "$e"
else
printf "[INVALID] %s\n" "$e"
fi
done
# Illustrative output (reviewed against documentation)
=== Auditing Email Formats via Bash Regex ===
[VALID] [email protected]
[INVALID] invalid-email@
[VALID] [email protected]
Native regex validation eliminates the overhead of executing grep or awk subshells thousands of times in deployment loops.
Automated Directory Cleanup: Pruning Old Builds with Inverted Globs
Clean deployment release folders while retaining only the current active release and protected directories.
#!/usr/bin/env bash
set -euo pipefail
shopt -s extglob
RELEASE_ROOT="/tmp/test_releases"
mkdir -p "$RELEASE_ROOT"/{release-101,release-102,release-103,shared,current}
CURRENT_ACTIVE="release-103"
echo "Pruning inactive releases in $RELEASE_ROOT (preserving $CURRENT_ACTIVE, shared, current)..."
cd "$RELEASE_ROOT"
# Match everything EXCEPT the active release, shared, and current:
echo "Files to purge:"
ls -d !("$CURRENT_ACTIVE"|shared|current)
rm -rf !("$CURRENT_ACTIVE"|shared|current)
echo "[SUCCESS] Cleanup complete. Remaining directories:"
ls -1
# Illustrative output (reviewed against documentation)
Pruning inactive releases in /tmp/test_releases (preserving release-103, shared, current)...
Files to purge:
release-101 release-102
[SUCCESS] Cleanup complete. Remaining directories:
current
release-103
shared
Extended globbing with !() provides clean, declarative file retention rules without writing fragile awk pipelines.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding bash inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
When using extended globs like rm -rf !(*.keep) with negation, test the pattern with ls first. If shopt -s extglob is accidentally unset, the shell may fail to parse the pattern or match unintended files.
When evaluating untrusted user input using the =~ operator, be cautious with regular expressions containing nested quantifiers (e.g. (a+)+$). While Bash uses the system's POSIX regex library, pathological regular expressions can still trigger exponential backtracking (ReDoS), hanging the shell script at 100% CPU.
Always quote the string operand (the left-hand side) of the =~ operator (e.g. [[ "$input" =~ $regex ]]) to prevent unexpected word splitting or syntax errors if the variable is empty or contains whitespace.
GNU/Linux, BSD, and BusyBox Implementation Differences
The =~ regex operator and the BASH_REMATCH array are specific to GNU Bash (version 3.0+). They do not exist in traditional POSIX shells like Dash (/bin/sh on Ubuntu/Debian). Scripts that use =~ must begin with a #!/bin/bash shebang.
Extended globbing (shopt -s extglob) is also a Bash/Korn shell extension. In pure POSIX /bin/sh scripts, you must use standard case statements with standard glob patterns (*, ?, [...]) or pipe into grep for pattern validation.
Troubleshooting Common Errors and Diagnostics
Regex fails to match because the pattern is quoted
Root Cause: In Bash 3.2+, quotes around the regex operand in [[ $str =~ "regex" ]] force Bash to treat metacharacters (*, +, ^, $) as literal characters.
Resolution: Remove the quotes or store the regex in a shell variable first.
# Incorrect (searches for literal '+'):
[[ "123" =~ "^[0-9]+$" ]]
# Correct:
REGEX='^[0-9]+$'
[[ "123" =~ $REGEX ]]
syntax error near unexpected token '(' when using extended globs
Root Cause: The script attempted to use extended globbing syntax like !(*.txt) before enabling it with shopt -s extglob.
Resolution: Enable extended globbing with shopt -s extglob at the top of your script.
shopt -s extglob
ls !(*.log)
[[ ... =~ ... ]] fails with 'operator expected' in /bin/sh
Root Cause: The script is being executed by Dash or a minimal POSIX shell (via /bin/sh) instead of Bash.
Resolution: Change the shebang to #!/bin/bash or run the script explicitly with bash script.sh.
#!/bin/bash
[[ "hello" =~ ^h ]]
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - Grep Multiple Patterns: Match Strings, Words, and Regex in Linux — Practical syntax, flags, and examples for
grep. - awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - type Command in Linux: Determine Command Interpretation and Path — Practical syntax, flags, and examples for
type. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
$REGEX ]]) avoids quoting discrepancies between Bash versions and protects against shell parser misinterpretation of spaces and metacharacters./bin/sh, use case statements with standard wildcards (case "$var" in [0-9]*) ... ;; esac) or pipe to grep -E.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides



Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!