I have a string in Bash:
string="My string"
How can I test if it contains another string?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
Where ??
is my unknown operator. Do I use echo and grep
?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
That looks a bit clumsy.
I use this function (one dependency not included but obvious). It passes the tests shown below. If the function returns a value > 0 then the string was found. You could just as easily return 1 or 0 instead.
I am not sure about using an if statement, but you can get a similar effect with a case statement:
You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:
Note that spaces in the needle string need to be placed between double quotes, and the
*
wildcards should be outside.