Ubuntu – Avoid duplicate pids while grepping for a pattern

grep

I have written a shell script that reads the updating logs and sends an email notification when there are OOM using do while loop.

I am able to get the email notification for OOM errors but every time a duplicate PID is getting generated for the email sent which is creating a huge no. of duplicate pids while I am grepping for that particular process/ Admin server (weblogic). PFB my script, is there any way I can avoid the duplicate PIDs and can get only parent PID while doing a grep.

#!/bin/sh
# Script to read the updating log file and send mail for any errors : LogCheck.sh
# SET VARIABLES
logfile=BEA_HOME/SERVERS/Admin.log
pattern="java.lang.OutOfMemoryError: Java heap space" 

#Read each line as it gets updating to the log file
tail -fn0 $logfile | while read line ; do 

    #check each line for our pattern
    echo "$line" | grep -i "$pattern"

    #Perform the below action if a line matches with our pattern
    if [ $? = 0 ]; 

    then
        #Send an email 
        echo "Found an error: $line" | mailx -s "please check the error" emailID 
    fi

done

Best Answer

You can use uniq or sort -u:

echo "$line" | grep -i "$pattern" | uniq