Table of Contents

BASH - Strings - Check if a String contains a Substring

Using double brackets with wildcard

string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi

NOTE: Spaces in the Substring need to be placed between double quotes.

The * asterisks should be outside the double quotes.

A simple comparison operator is used (i.e. ==), not the regex operator =~.

The comparison can be reversed by just switching to != in the test.


Regex approach

string='My string';
 
if [[ $string =~ "My" ]]; then
   echo "It's there!"
fi

Using a case statement

case "$string" in 
  *foo*)
    # Do stuff
    ;;
esac