How to check if a string contains a substring in Bash How to check if a string contains a substring in Bash bash bash

How to check if a string contains a substring in Bash


You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:

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

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside. Also note that a simple comparison operator is used (i.e. ==), not the regex operator =~.


If you prefer the regex approach:

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


I am not sure about using an if statement, but you can get a similar effect with a case statement:

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