One of the most common operations when working with strings in Bash is to determine whether or not a string contains another string.
In this article, we will show you several ways to check if a string contains a substring.
The easiest approach is to surround the substring with asterisk wildcard symbols (asterisk) *
and compare it with the string. Wildcard is a symbol used to represent zero, one or more characters.
If the test returns true
, the substring is contained in the string.
In the example below we are using the if statement and the equality operator (==
) to check whether the substring SUB
is found within the string STR
:
#!/bin/bash
STR='GNU/Linux is an operating system'
SUB='Linux'
if [[ "$STR" == *"$SUB"* ]]; then
echo "It's there."
fi
Copy
When executed the script will output:
It's there.
Instead of using the if statement you can also use the case statement to check whether or not a string includes another string.
#!/bin/bash
STR='GNU/Linux is an operating system'
SUB='Linux'
case $STR in
*"$SUB"*)
echo -n "It's there."
;;
esac
Copy
Another option to determine whether a specified substring occurs within a string is to use the regex operator =~
. When this operator is used, the right string is considered as a regular expression.
The period followed by an asterisk .*
matches zero or more occurrences any character except a newline character.
#!/bin/bash
STR='GNU/Linux is an operating system'
SUB='Linux'
if [[ "$STR" =~ .*"$SUB".* ]]; then
echo "It's there."
fi
Copy
The script will echo the following:
It's there.
#string #linux #java #javascript