Bash Script to Check if String Contains Substring
if [[ "$string" == *"$substring"* ]]; then to check if $string contains $substring in Bash.Examples
How to Think About It
* wildcards around the substring.Algorithm
Code
#!/bin/bash string="hello world" substring="world" if [[ "$string" == *"$substring"* ]]; then echo "Substring found" else echo "Substring not found" fi
Dry Run
Let's trace the example where string='hello world' and substring='world' through the code
Set variables
string='hello world', substring='world'
Check condition
Does 'hello world' match pattern '*world*'? Yes
Print result
Output: 'Substring found'
| Step | String | Substring | Condition Result | Output |
|---|---|---|---|---|
| 1 | hello world | world | N/A | N/A |
| 2 | hello world | world | True | N/A |
| 3 | hello world | world | True | Substring found |
Why This Works
Step 1: Pattern Matching
The [[ "$string" == *"$substring"* ]] uses wildcards * to check if $substring appears anywhere inside $string.
Step 2: Conditional Execution
If the pattern matches, the if condition is true, so the script prints 'Substring found'.
Step 3: Else Case
If the substring is not found, the condition is false, and the script prints 'Substring not found'.
Alternative Approaches
#!/bin/bash string="hello world" substring="world" echo "$string" | grep -q "$substring" if [ $? -eq 0 ]; then echo "Substring found" else echo "Substring not found" fi
#!/bin/bash string="hello world" substring="world" case "$string" in *"$substring"*) echo "Substring found" ;; *) echo "Substring not found" ;; esac
Complexity: O(n) time, O(1) space
Time Complexity
The check scans the main string once to find the substring, so it runs in linear time relative to the string length.
Space Complexity
No extra memory is needed besides the input strings; the check is done in place.
Which Approach is Fastest?
The built-in [[ ]] pattern matching is fastest and simplest; grep involves spawning a process, which is slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| [[ ]] with wildcards | O(n) | O(1) | Simple, fast substring check in modern Bash |
| grep command | O(n) | O(1) | Compatibility with older shells, supports regex |
| case statement | O(n) | O(1) | Readable pattern matching alternative |