Home > Blockchain >  linux compare two variable
linux compare two variable

Time:01-19

The script found error but it always goes to Else condition "No Found Error". Am I missing how to compare two variables?

ERROR="Error:"
for i in `find /logs -mtime -1`
do
CHECK=`cat $i |grep -i "Error"|cut -f 1 -d " "`
if [ "$CHECK" == $ERROR ]
then
  echo "Found Error"
else
 echo "Not Found Error"
fi
done

CodePudding user response:

Did you tried something like if [[ "$CHECK" == $ERROR ]] ?

To simply detect error without printing the error message, you can use

CHECK=$(cat $i | grep "Error" | wc -l)
if [[ $CHECK -ne 0 ]]
then
   echo "Found error"
else
   echo "Not found error"
fi

CodePudding user response:

You are using grep -i for case-insensitive matching, but then testing the result for exact equality with the string Error:. If the case-insensitive matching is important then the exact equality test is not an appropriate complement.

You are also capturing a potentially multi-line output and comparing it to a string that can be the result only of a single-line output.

And you are matching "Error:" anywhere on the line, but assuming that it will appear at the beginning.

Overall, you are going about this a very convoluted way, as grep tells you via its exit status whether it found any matches. For example:

#!/bin/bash

for log in `find /logs -mtime -1`; do
  if grep -i -q '^Error:' "$log"; then
    echo "Found Error"
  else
    echo "Not Found Error"
  fi
done

CodePudding user response:

There is two things that I would advise and may fix your issue:

  1. Add #!/bin/bash on the first line, to make sure it is interpreted as bash and not sh. Many time I had trouble with comparison because of this

  2. When comparing two variables, uses double brackets ([[ and ]]) Also, if it strings, always put quotes "$ERROR" around it. It's missing for the $ERROR variable.

Look at the other answers also, there are many ways to do the same thing in a much simpler way.

Note: When comparing numbers you should use -eq

  •  Tags:  
  • Related