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.
Compatible answer
As there is already a lot of answers using Bash-specific features, there is a way working under poorer-featured shells, like busybox:
In practice, this could give:
This was tested under bash, dash, ksh and ash (busybox), and the result is always:
Into one function
As asked by @EeroAaltonen here is a version of same demo, tested under the same shells:
Then:
Notice: you have to escape or double enclose quotes and/or double quotes:
Simple function
This was tested under busybox, dash and, of course bash:
That's all folks!
Then now:
... Or if the submitted string could be empty, as pointed by @Sjlver, the function would become:
or as suggested by Adrian Günter's comment, avoiding
-o
switche:With empty strings:
This also works:
And the negative test is:
I suppose this style is a bit more classic -- less dependent upon features of Bash shell.
The
--
argument is pure POSIX paranoia, used to protected against input strings similar to options, such as--abc
or-a
.Note: In a tight loop this code will be much slower than using internal Bash shell features, as one (or two) separate processes will be created and connected via pipes.
This Stack Overflow answer was the only one to trap space and dash chars:
How about this:
As Paul mentioned in his performance comparison:
This is POSIX compliant like the 'case "$string" in' answer provided by Marcus, but is slightly easier to read than the case statement answer. Also note that this will be much much slower than using a case statement, as Paul pointed out, don't use it in a loop.