test egrep not found

Hi,

I want to return failure from my script if a string is NOT found in a file, but I can't work out how to negate my "if". At the moment I have :

if (egrep -i 'search string' filetosearch); then
echo "found"
else
return 2
fi

How can I get rid of the echo bit and just test for "string not found" ? I already know I can use egrep -v to return lines not containing the string, but I actually just want to fail if the search string is not in the file anywhere. Thanks.

#! /usr/bin/ksh
egrep -i "string" file_name
if [ $? -eq 0 ]
then
echo "Found"
else
return 2
fi

That's a Useless Use of Test $?. if already examines the exit code $? from the command it executes, so it's simpler and more straightforward to do

if egrep -i "string" file_name
then
    echo Found
else
    return $?
fi

To negate an if, use an exclamation mark.

if ! egrep -i "string" file_name
then
    return $?
fi

There's another shorthand you should know about: the "or" connective. It executes the second command if the first command fails.

egrep -i "string" file_name >/dev/null || return $?

There is also && "and" which operates the other way around.

(I added redirection to /dev/null as egrep is used simply for its return value here. You don't want it to actually print any matches. If your egrep has the -q option, you could use that too.)

Great, thanks. I had tried ! already as this seemed pretty obvious but it didnt seem to work .. but now it is ! Thanks guys ...

the best ....