PDA

View Full Version : grep for string and test if successfully or not


b-boy
February 17th, 2009, 07:20 AM
Hi guys I am using grep in a bash script to look for a string and i would like to check if the string was found

so my script goes a little some thing like this !!!


grep bboy /var/log/messages
echo $?


so assumed that since the string bboy was not in /var/log/messages I would get the value higher than 0 but wether or not the string is in /var/log/messages I still get the valure 0

why?

albandy
February 17th, 2009, 07:27 AM
MSG=$(grep bboy /var/log/messages)

if [ "$MSG" == "" ]
then
echo "No results"
fi

b-boy
February 17th, 2009, 07:34 AM
MSG=$(grep bboy /var/log/messages)

if [ "$MSG" == "" ]
then
echo "No results"
fi

thanks

Yuzem
February 17th, 2009, 02:17 PM
You can use the "-m 1" flag that exits at the first match:

if ! [[ $(grep -m 1 bboy /var/log/messages) ]]; then
echo no results
fi

lavinog
February 17th, 2009, 08:14 PM
i use something like this:

grep -q "string" filename&&{
echo "string found"
other commands
...
}

glotz
February 17th, 2009, 09:56 PM
I suppose you get 0 in both cases because that's the exit code (http://en.wikipedia.org/wiki/Exit_code) for having successfully run the command. You could use this insteadif grep -m1 bboy /var/log/messages>/dev/null
then
echo It\'s there.
else
echo Not there.
fi