While you working with string in Bash need to check whether a string contains another string. In this guide, we will show you multiple ways to check if a string contains a substring in bash scripting.
It is easy to use asterisk wildcard symbols (asterisk)
* to compare with the string. Wildcard is a symbol used to represent zero, one or more characters. If the string contained the string it will returns
Let’s see an example, we are using if statement with equality operator (
==) to check whether the substring
SUBSTR is found within the string
#!/bin/bash STR='Ubuntu is a Linux OS' SUBSTR='Linux' if [[ "$STR" == *"$SUBSTR"* ]]; then echo "String is there." fi
It will show following output:
String is there.
Use the case operator
You can use the case statement instead of if statement to check whether a string includes or not to another string.
#!/bin/bash STR='Ubuntu is a Linux OS' SUBSTR='Linux' case $STR in *"$SUBSTR"*) echo -n "String is there." ;; esac
Using Regex Operator
Another way is to use the regex operator
=~ to check whether a specified substring occurs within a string. 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='Ubuntu is a Linux OS' SUBSTR='Linux' if [[ "$STR" =~ .*"$SUBSTR".* ]]; then echo "String is there" fi
The script will echo the following:
String is there
The grep command can also be used to find strings in another string.
In the below example, we are giving string in the
$STR variable to grep and check if the string
$SUBSTR is found within the string. It will return
#!/bin/bash STR='Ubuntu is a Linux OS' SUBSTR='Linux' if grep -q "$SUB" <<< "$STR"; then echo "String is there" fi
In this article, you learned how to check a substring contains in the given string using multiple ways in Bash script.
If you have any questions or feedback, feel free to leave a comment.
Leave a Reply