To check if a string contains a substring in Bash, you can use the following methods:
1. Using [[ ]]
with Wildcard Matching
string="Hello World"
substring="World"
if [[ "$string" == *"$substring"* ]]; then
echo "Substring found!"
else
echo "Substring not found."
fi
Explanation:
*"$substring"*
acts as a wildcard pattern to match the substring anywhere in the string.- Quotes around variables prevent globbing or splitting issues.
- Best for simple substring checks.
2. Using =~
(Regex Operator)
string="Hello World"
substring="Wor"
if [[ "$string" =~ "$substring" ]]; then
echo "Substring found!"
fi
Notes:
- The
=~
operator treats the substring as a regular expression. - Escape regex special characters (e.g.,
.
,*
,+
) if you want literal matches:
substring="a\.c" # Matches "a.c" literally (not "abc")
3. Using case
Statements
string="Hello World"
substring="lo W"
case "$string" in
*"$substring"*) echo "Found" ;;
*) echo "Not found" ;;
esac
Use Case:
- Useful in POSIX-compliant scripts (works in
sh
andbash
).
4. Using grep
(External Command)
string="Hello World"
substring="World"
if echo "$string" | grep -q "$substring"; then
echo "Substring found!"
fi
Notes:
-q
suppresses output (quiet mode).- Avoid this method in performance-critical scripts (spawns a subshell).
Key Differences
Method | Pros | Cons |
---|---|---|
Wildcard ([[ ]] ) | Fast, no subshell, simple | Bash-specific syntax |
Regex (=~ ) | Flexible (regex support) | Requires escaping special characters |
case Statement | POSIX-compliant | Verbose for simple checks |
grep | Works in all shells | Overhead of external process |
Examples
Check for Multiple Substrings
string="Hello World"
if [[ "$string" == *"Hello"* && "$string" == *"World"* ]]; then
echo "Both substrings found!"
fi
Case-Insensitive Check
shopt -s nocasematch # Enable case-insensitive matching
string="Hello World"
substring="world"
if [[ "$string" =~ "$substring" ]]; then
echo "Found (case-insensitive)!"
fi
shopt -u nocasematch # Disable afterward
Summary
- Preferred Method: Use
[[ "$str" == *"$substr"* ]]
for simplicity and efficiency. - Regex Use: Opt for
=~
if you need pattern matching (e.g., partial words, wildcards). - Avoid
grep
unless necessary for compatibility.