How to Check if String Contains Substring in Bash
Quick Answer: Check if String Contains Substring
Use the [[ operator with wildcards: if [[ $string == *"substring"* ]]; then echo "found"; fi. This is the fastest and cleanest method in modern Bash.
Quick Comparison: Substring Checking Methods
| Method | Speed | Case-sensitive | Best For |
|---|---|---|---|
| [[ == *…* ]] | Fastest | Yes | Most cases |
| Parameter expansion | Very fast | Yes | Avoiding pipes |
| grep | Medium | Optional (-i flag) | Regex patterns |
| =~ | Very fast | Yes | Complex patterns |
Bottom line: Use [[ $str == *"pattern"* ]] for best performance and clarity.
Check if a string contains a substring using various methods in Bash.
Method 1: Using [[ ]] (Recommended)
The [[ operator (double brackets) is Bash-specific and offers the cleanest syntax for substring checking. The wildcards *pattern* match anything before and after the pattern, so the condition becomes “does the string contain this pattern anywhere?”
text="Hello, World!"
if [[ $text == *"World"* ]]; then
echo "String contains 'World'"
fi
This is fast because it’s built into Bash (no external commands), readable because the syntax is straightforward, and flexible because it supports wildcards and patterns. The asterisks mean “zero or more of any character,” so *World* means “anything, then World, then anything.”
Case-insensitive checking is also straightforward—convert to lowercase with ${text,,}:
if [[ ${text,,} == *"world"* ]]; then
echo "Contains 'world' (case-insensitive)"
fi
The ${text,,} syntax converts the entire string to lowercase (Bash 4+), then checks against the lowercase pattern. This is much simpler than older workarounds using tr or sed.
When to Use [[ ]] Substring Checking
Use this method when:
- You need simple substring checking
- Performance matters
- You’re using Bash 3.2 or newer
- You don’t need complex regex patterns
Method 2: Using Parameter Expansion
text="Hello, World!"
if [ "$text" != "${text#*World}" ]; then
echo "String contains 'World'"
fi
Method 3: Using grep
text="Hello, World!"
if echo "$text" | grep -q "World"; then
echo "String contains 'World'"
fi
Case-insensitive:
if echo "$text" | grep -iq "world"; then
echo "Contains 'world' (case-insensitive)"
fi
Method 4: Using Regular Expression
text="Hello, World!"
if [[ $text =~ World ]]; then
echo "String contains 'World'"
fi
Practical Examples
Check if Variable is Empty
if [[ -z $var ]]; then
echo "Variable is empty"
fi
Extract Matches
text="My email is john@example.com"
if [[ $text =~ ([a-z]+@[a-z]+\.[a-z]+) ]]; then
echo "Found email: ${BASH_REMATCH[1]}"
fi
Search Multiple Patterns
text="error in file.txt"
if [[ $text == *"error"* || $text == *"warning"* ]]; then
echo "Found error or warning"
fi
Performance Comparison
- [[ ]]: Fastest (built-in Bash)
- Parameter expansion: Fast (no external command)
- grep: Slower (external process)
- Regex: Medium speed (pattern matching)
Use [[ $text == *"pattern"* ]] for best performance.