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.
1. Using Wildcards
The simplest way to check if a string contains given substring is by using Bash wildcards.
#!/bin/bash
string='Example text...'
substring='text'
if [[ "$string" == *"$substring"* ]]; then
echo "The string contains the substring."
fi
Run in command line:
./script.sh
Output:
The string contains the substring.
2. Using Regex
Another simple solution is to use regex operator (=~).
#!/bin/bash
string='Example text...'
substring='text'
if [[ "$string" =~ .*"$substring".* ]]; then
echo "The string contains the substring."
fi
Run in command line:
./script.sh
Output:
The string contains the substring.