How to find a substring in a string in bash?



METHOD 1:  wildcards)

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

OUTPUT:

It's there!

Note that spaces in the needle string need to be placed between double quotes, and the *wildcards should be outside.


METHOD 2:  regex approach

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

OUTPUT:

It's there!


Method 3:  case statement

case $(pwd) in  *path) echo "ends with path";;  path*) echo "starts with path";;  *path*) echo "contains path";;  *) echo "this is the default";;esac