Often you may want to use Bash to check if a string contains a specific substring.
You can use the following syntax to do so:
if [[ $my_string == *"Mav"* ]]
then
echo "String contains substring"
else
echo "String does not contain substring"
fi
This particular example will check if the string variable named my_string contains the substring “Mav” and returns one of the following as output:
- “String contains substring”
- “String does not contain substring”
Note that this syntax uses wildcard characters ( * ) on either side of the substring to indicate that any characters may come before or after the substring in the original string as well.
Note: When using wildcard characters, you must use double brackets ( [[ ) with an if statement. Single brackets will produce an error.
The following example shows how to use this syntax in practice.
Example: How to Check if String Contains Substring in Bash
Suppose we have a string variable named my_string in Bash that contains the following text:
- “The Dallas Mavericks”
Suppose that we would like to check if this string contains the substring “Mav” anywhere in the string.
We can use the following syntax to do so:
my_string="The Dallas Mavericks"
if [[ $my_string == *"Mav"* ]]
then
echo "String contains substring"
else
echo "String does not contain substring"
fi
The following screenshot shows how to use this syntax in practice:

This returns “String contains substring” since the string variable does indeed contain the substring “Mav” in the larger string.
Suppose instead that we check if the string contains the substring “Lakers” anywhere in the string:
my_string="The Dallas Mavericks"
if [[ $my_string == *"Lakers"* ]]
then
echo "String contains substring"
else
echo "String does not contain substring"
fi
The following screenshot shows how to use this syntax in practice:

This returns “String does not contain substring” since the string variable does not contain the substring “Lakers” anywhere in the string.
Feel free to replace “Lakers” with any other substring that you’d like.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Check if String Starts with Specific Value
Bash: How to Check if String Ends with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String
