Home > Net >  How to grep errors in log and print 1 line for all errors in shell script?
How to grep errors in log and print 1 line for all errors in shell script?

Time:04-26

I want to check errors while reading a log file in shell script, and if there are some errors, I want it to echo 'Please check errors' and output it in a file, but the issue is if there are many errors it prints 'Please check errors' for every error,

ex: if there are 5 errors in the file, it prints 'Please check errors' 5 times like this:

Please check errors Please check errors Please check errors Please check errors Please check errors

I want it to print only 1 line regardless how many errors were found.

**

FILE=/home/user/logs/file.log

    if [ ! -f $FILE ]
    then echo 'No File Exists' > /home/user/error.txt
    else tail $FILE  | \
         while read line ; do
            echo $line | grep -i "error"
              if [ $? = 1 ]
              then echo Please check Errors in: $FILE > /home/user/error.txt
              fi
         done
    fi
**

CodePudding user response:

You have the basic idea, you just need to rearrange a bit. First confirm whether errors exist with grep -q 'error' "$FILE" and then if errors exist write the "Please check Errors" prompt and output the lines containing errors.

Why not:

if grep -qi 'error' "$FILE"; then
  printf "Please check Errors in %s\n" "$FILE"
  grep -i 'error' "$FILE"
fi

There is no loop and no calling grep every iteration of the loop. Simply one call to grep -q to check if "error" exists, and then output your heading and each line containing "error" with the second call to grep.

If you want to write the output to a file, just redirect all output to a new file.

  • Related