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 the main string"
fi
Find string containing substring using regular expression
=~
operator is used for searching substrings 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 the main string"
fi
Substring checks using the grep command
The 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 the main string"
fi