Monitor a file and send mail

I want to monitor the maillog file in real time and send a mail when a certain grep condition is met. Every time the grep condition is met a mail will be sent. I wish to ignore all grep conditions 30 mins after each mail and thereafter continue monitoring.

For example:

  1. Condition is met, mail is sent
  2. 30 mins no mail even if condition is met.
  3. After 30 mins again condition is met and a mail is triggered.
  4. Again for next 30 mins no mail even if condition is met.

and so on.

I am doing the following:

tail -F -n0 /var/log/maillog | \
 grep -v --line-buffered 'status=sent' | \
 grep --line-buffered -v 'relay=local' | \
 grep --line-buffered 'relay=' | \
 while read line
 do
    echo "$line" | \
    mail -s Test mail@group.com
 done

Now i am not sure how to prevent mail sending 30 mins after the event is triggered.

How about we remember where we are upto in the maillog and only print new stuff.
That way we can sleep for 30mins and the resume checking:

UPTO=0
MAILFILE=/var/log/maillog
while [ -f "$MAILFILE" ]
do
    FSZ=$(wc -l < "$MAILFILE")

    if [ $FSZ -lt $UPTO ]
    then
        # File has shrunk!
        # most likely been truncated - start from beginning again.
        UPTO=0
    fi

    found=$( awk -v START=$UPTO -v FINISH=$FSZ '
       NR <= START || NR > FINISH { next }
       /status=sent/ || /relay=local/ { next }
       /relay=/ { print }' "$MAILFILE" )

    if [ -z "$found" ]
    then
       # Wait for a minute for maillog to grow a bit
       sleep 60
    else
       echo "$found" | mail -s Test mail@group.com

       # No more emails for 30mins
       sleep 1800

       # If you don't want to be notified about any other
       # occurances within this 30min period uncomment below
       # FSZ=$(wc -l /var/log/"$MAILFILE")
    fi
    UPTO=$FSZ
done