grep in the if condition

Hi,
In this code can able to match the pattern without case sensitive. Is that possible?
if u knw plz help me...
code:

echo "Enter name to search"
read n
if [ grep $n file ];
echo "name found"
else
echo "Not Found"
fi

Have you checked: "grep -i" option?

echo "Enter name to search"
read n
countFound=`grep -ic "${n}" file`
if [ ${countFound} -ne 0 ]
then
     echo "name found"
else
     echo "Not Found"
fi

-i
--ignore-case
Ignore case distinctions in both the PATTERN and the input files.

You don't need to shove an entire command into backticks and force it to output a number to stdout just to tell if it succeeded or failed. grep, like nearly any other command, returns a code directly.

if grep -i "${n}" file > /dev/null
then
        echo "name found"
else
        echo "name not found"
fi

You are right! But that is the way I like to do it! I think the code is easier to read this way! :wink:

1 Like

It took me a while to figure out the goal in all those options and backticks. Perhaps it seems obvious to you because putting things in backticks is how you solve most shell problems? It's not the simplest, fastest, or most direct, just the way you're used to. Hammer, nail, etc.

I know that there are better ways (simplest, fastest, most direct, etc) to do scripting and also that the "$()" is much better than using backsticks!

But as you commented, that's the way I am used to! :smiley:

for this code im getting error like Grep:0652-033 Cannot open name

Check your filename.