Click to See Complete Forum and Search --> : Testing strings in BASH
TobyR
05-30-2005, 11:02 AM
I've read that * is wild card in BASH for one or more characters, and that "=" is a test for the equivalence of strings. I'm trying to test whether $TESTSTRING contains a certain pattern of characters ("abc") and so am using
if [ "$TESTSTRING" = *abc* ]
then
echo "True"
fi
... and am not getting 'True'. What basic error am I making?
thanks.
asarch
05-30-2005, 11:24 AM
What about this:
#!/bin/bash
TESTSTRING='justlinuxisthebestplaceabcdefghijkl'
if $( echo $TESTSTRING | grep --quiet 'abc' )
then
echo true 'abc'
fi
if $( echo $TESTSTRING | grep --quiet 'oby' )
then
echo true 'oby'
fi
TobyR
05-30-2005, 01:35 PM
Yup, that did it. Many thanks.
bwkaz
05-30-2005, 09:57 PM
Originally posted by TobyR
I'm trying to test whether $TESTSTRING contains a certain pattern of characters ("abc") and so am using
if [ "$TESTSTRING" = *abc* ]
then
echo "True"
fi
... and am not getting 'True'. What basic error am I making? You can't do wildcarding with the "[" builtin command (or the "test" builtin, for that matter).
If you want to match a regular expression, then use grep, as asarch did. (But that wastes one or maybe two processes.)
If you only want to match a glob pattern (which seems to be what you're describing), then use case. It's a shell builtin, so you don't waste a process, and if you aren't using the full regular-expression language anyway, then why use it? ;) Anyway, case looks like this:
case "$TESTSTRING" in
*abc*)
echo "True"
;;
*)
echo "False"
;;
esac The string before the ) is checked to see if it's a valid glob match to the "$TESTSTRING" value. If so, then the commands that follow the ) are executed, until the first ;; sequence. Then control skips to the esac.
If the first pattern doesn't match, then the shell skips to the next pattern and tries to evaluate it. (So in effect, a *) pattern means "if nothing else matches, use this".)
asarch
05-31-2005, 12:20 AM
You can also do this if you want to emulate
strstr(3) (http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=linux&db=man&fname=/usr/share/catman/man3/strstr.3.html&srch=strstr):
#!/bin/bash
TESTSTRING='justlinuxisthebestplaceabcdefghijkl'
function strstr ( )
{
echo $1 | grep --quiet $2
}
if $( strstr $TESTSTRING 'abc' )
then
echo true abc in function strstr
fi
if $( strstr $TESTSTRING 'oby' )
then
echo true oby in function strstr
fi