0

I have a log file created while running a script.

I want to check the same log file for any messages with 'Msg ....' and exit the code except with this 'Msg 2714'.

So, I had added the below code into my script:

Some line of code before

rc1=`grep -v 'Msg 2714' $Logfilename`
rc2=`grep -i 'Msg' $rc1`

if [ $rc2 -ne "" ]
then
    echo "Error message, some query has failed"
    exit
fi

But, i have been encountering through a problem with the grep command, even though the second grep returns null the exit code/return code is '1' so the- "if commands fails and the exists the script".

Please provide any suggestion if any thing was wrong here?

Thank you!

Suresh
  • 3

1 Answers1

3

Your script uses the value of $rc1 as a filename, but this is the output of grep.

To feed the output of the first grep into another grep, use a pipe:

grep -v ... filename | grep ...

Instead of saving the result of grep in variables (which can presumably be quite big), let the if test act directly on the result of running this pipeline:

if grep -v -F 'Msg 2714' "$Logfilename" | grep -q -F Msg; then
    echo 'Error message, some query has failed' >&2
    exit 1
fi

This uses the exit status of the pipeline (which will be the exit status of grep -q) to determine whether the script should output the error message and quit. No data needs to be stored in variables.

grep -q will not output anything but will exit successfully if the given pattern matches. I've also used -F with both invocations of grep as we are matching strings, not regular expressions.

I'm also following the general guideline that error messages are generated on the standard error stream (with echo ... >&2 in this case) and that the script will terminate with a non-zero exit status upon a fatal error.

Also possibly relevant, regarding your non-quoting of variable expansions:

Kusalananda
  • 333,661
  • 1
    Thank you very much. I have used unusual greps to complicate the code. Read your complete explanation and man page about grep -q option. It worked fine for me now.. thank you. – Suresh Oct 25 '18 at 14:31