trapping error for a grep in for a loop

How can I trap and print "cannot find the pattern" when the grep is unable to find the specified pattern in the file using the for loop below ?

Any help would be appreciated.

bash3.4> cat test_file
apple
orange
pineapple
blackberry

script:

for x in `grep -n "mango" test_file |cut -d":" -f1`
do
echo $x
done
:b:

There might be other better ways to do it, but this works too...

x=`grep -n "mango" test_file |cut -d":" -f1`
if [[ -z $x ]]; then
   echo "cannot find the pattern"
   return 1;
else 
   echo "match found"
fi
for y in $x
do
   echo $y
done


regards,
Arun.

Grep will return 1 if it can't mind a match, but the problem is you're piping it thought "cut", which doesn't fail. If you said

for x in `grep -n "mango" test_file`
do
echo $x
done
echo $?
 
1

Then the "exit code" from the for loop will be 1

or

for x in `grep -n "mango" test_file |cut -d":" -f1`
do
if [ -n "$x" ];then
echo $x String is not empty
else
echo $x String is empty
fi
done

I hope this help!

First of all Let me thank you guys for posting the solutions so quickly.
I have tried each one of the code that was posted.

although arunsoman80 solution I liked apprently it does not work because of the return 1 and "-z" switch in the if statement.

scottn solution makes me twist the logic.

research3 solution fits perfect !

whatever it is, all you guys seem to be real knowlegeble and seem to have a good grip on unix

Thanks once again.