Check if String contains Substring
To check if a string contains a substring in Bash, use comparison operator ==
with the substring surrounded by *
wildcards.
Syntax
The syntax of expression to check if string str
contains substring substr
is
</>
Copy
$str == *"$substr"*
While using the above expression as a condition in If statement, use double square brackets around the expression.
Example
String contains Substring
In the following script, we take two strings: str
and substr
, and check if str
contains substr
. We take values for the strings such that substr
is present in str
.
Example.sh
</>
Copy
str="hello world"
substr="world"
if [[ $str == *"$substr"* ]];
then
echo "String contains substring."
else
echo "String does not contain substring."
fi
Output
String contains substring.
String contains Substring
Now, let us take values for the strings such that substr
is not present in str
.
Example.sh
</>
Copy
str="hello world"
substr="good"
if [[ $str == *"$substr"* ]];
then
echo "String contains substring."
else
echo "String does not contain substring."
fi
Output
String does not contain substring.
Conclusion
In this Bash Tutorial, we have learnt how to check if a string contains a substring or not in Bash shell.