问题描述:

I am trying to see if I found something using grep or not with this

found=`grep -F "something" somefile.txt`

if ((${#found} == 0)); then

echo "Not Found"

else

echo "Found"

fi

I succeeded using above logic that if grep found something it stores the output in found variable but the issue I am facing is with if condition. Whenever found=0 it gives me some error like that

final.sh: 13: final.sh: 0: not found

FYI: final.sh is the script name

网友答案:

To check whether some string is in your file, you can use the return status from grep

grep -q something somefile.txt
if [ $? -eq 0 ]
then
  echo "found"
else
  echo "not found"
fi

a shorter form will be

grep -q something somefile.txt && echo found || echo not found
网友答案:

The problem is that you're writing bash specific code, but running it with sh. In bash, (( .. )) is an arithmetic context, while in POSIX sh, it's merely two nested subshells, causing it to try to execute the number as a command.

You can run it with bash instead of sh by specifying #!/bin/bash in the shebang, and/or using bash yourfile instead of sh yourfile if you invoke it that way.

The correct way for your example, however, is to use grep's exit status directly:

if grep -q something somefile
then
  echo "found"
else
  echo "not found"
fi
网友答案:
found=$(grep -F "something" somefile.txt)
if [ $? = 0 ]; then # $? is the return status of a previous command. Grep will return 0 if it found something, and 1 if nothing was found.
    echo "Something was found. Found=$found"
else
    echo 'Nothing was found'
fi

I find this code more elegant than other answers.
But anyway, why are you writing in sh? Why don't you use bash? Are you sure that you need that portability? Check out this link to see if you really need sh

网友答案:

Here's how I do that sort of thing:

found=$(grep -F "something" somefile.txt)

if [[ -z $found ]]; then
    echo "Not found"
else
    echo "Found"
fi
相关阅读:
Top