How to Check if String Contains Substring in Bash
In bash, you can check if a string contains a substring using the
[[ $string == *substring* ]] syntax inside an if statement. This tests if substring appears anywhere within $string.Syntax
The basic syntax to check if a string contains a substring in bash is:
if [[ $string == *substring* ]]; then— checks ifsubstringis anywhere in$string.then— starts the block of code to run if the condition is true.fi— ends theifblock.
bash
if [[ $string == *substring* ]]; then echo "Substring found" fi
Example
This example shows how to check if the word hello is inside a string variable and prints a message if it is found.
bash
#!/bin/bash string="hello world" if [[ $string == *hello* ]]; then echo "The string contains 'hello'" else echo "The string does not contain 'hello'" fi
Output
The string contains 'hello'
Common Pitfalls
Common mistakes include:
- Using single brackets
[ ]instead of double brackets[[ ]], which does not support pattern matching with*. - Not quoting variables can cause word splitting or globbing issues.
- Using
==inside single brackets[ ]is not POSIX compliant; prefer=there.
bash
# Wrong way (does not work as expected): string="hello world" if [ "$string" == *hello* ]; then echo "Found" fi # Right way: if [[ $string == *hello* ]]; then echo "Found" fi
Output
Found
Quick Reference
| Usage | Description |
|---|---|
| [[ $string == *substring* ]] | True if substring is anywhere in string |
| [[ $string != *substring* ]] | True if substring is NOT in string |
| if [[ $string == *sub* ]]; then ... fi | Run code if substring found |
| Use double brackets [[ ]] for pattern matching | Required for wildcard matching with * |
Key Takeaways
Use double brackets [[ ]] with wildcards * to check substring presence in bash.
Always quote variables to avoid word splitting and globbing issues.
Single brackets [ ] do not support pattern matching with * for substring checks.
Use == inside [[ ]] for pattern matching, not inside [ ].
Test your script with different strings to ensure correct substring detection.