EN
Bash - check if string contains substring
3 points
In this article, we would like to show you how to check if string contains substring in Bash.
The simplest way to check if a string
contains given substring
is by using Bash wildcards.
xxxxxxxxxx
1
2
3
string='Example text...'
4
substring='text'
5
6
if [[ "$string" == *"$substring"* ]]; then
7
echo "The string contains the substring."
8
fi
Run in command line:
xxxxxxxxxx
1
./script.sh
Output:
xxxxxxxxxx
1
The string contains the substring.
Another simple solution is to use regex operator (=~
).
xxxxxxxxxx
1
2
3
string='Example text...'
4
substring='text'
5
6
if [[ "$string" =~ .*"$substring".* ]]; then
7
echo "The string contains the substring."
8
fi
Run in command line:
xxxxxxxxxx
1
./script.sh
Output:
xxxxxxxxxx
1
The string contains the substring.