In this tutorial, the Bash script checks if the string contains a substring.
There are multiple ways to check if a string contains a substring.
Check substring exists in a string using the comparison operator
-
string variable is defined with text
-
using if statements, compare string with substring using comparison operator(
==
) and wildcard(*
) -
finally, print the string if the string contains
mainstring='Welcome to w3schools'
if [[ $mainstring == *"w3schools"* ]]; then
echo "w3schools exists in main string"
fi
Find string contains substring using regular expression
=~
operator used for searching substring for a given string.
used if block in a batch script.
Here is an example code
mainstring='Welcome to w3schools'
if [[ $mainstring =~ "w3schools" ]]; then
echo "w3schools exists in main string"
fi
Substring checks using grep command
grep
command searches for a given string and is piped to the main string to compare it.
mainstring='Welcome to w3schools'
if echo "$mainstring" | grep -q "w3schools"; then
echo "w3schools exists in main string"
fi