davidsheldon davidsheldon - 4 years ago 311
Bash Question

String contains in Bash

Using Bash, I have a string:

string = "My string"

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then
echo "It's there!"

is my unknown operator. Do I use echo and

if echo "$string" | grep 'foo'; then
echo "It's there!"

That looks a bit clumsy.

Answer Source

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"* ]]
  echo "It's there!";

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download