Bash Find Out IF a Variable Contains a Substring

To find out if a variable contains a substring in Bash, you can use the [[ operator along with the == operator or the =~ operator.

Here is an example using the == operator:

#!/bin/bash

string="Hello World"

if [[ "$string" == *ello* ]]; then
echo "Substring found"
else
echo "Substring not found"
fi

In this example, the *ello* pattern matches any string that contains the substring “ello”. If the substring is found, the script will output “Substring found”. Otherwise, it will output “Substring not found”. (www.sellerlabs.com)

Here is an example using the =~ operator and a regular expression:

#!/bin/bash

string="Hello World"

if [[ "$string" =~ "llo Wo" ]]; then
echo "Substring found"
else
echo "Substring not found"
fi

In this example, the regular expression "llo Wo" matches the substring “llo Wo” in the string. If the substring is found, the script will output “Substring found”. Otherwise, it will output “Substring not found”.

Note that in both examples, the double quotes around the variable are necessary to prevent word splitting and globbing of the string. If you omit the quotes, the script may not work correctly for certain input strings.

Leave a Comment