user3164754
user3164754

Reputation: 215

Limit cron from sending a mail for 5 mins in linux/shell

I have a shell script that I am running as a cron every minute. My script checks for logs generated in the last one minute and send me a mail if logs generated are more than a certain limit. Now, in times of an issue there could hundreds of files generated every minute. And that's where I need some help. I don't want the cron to send me a mail every minute logs are generated. If it sends one mail, it can wait 5 mins or 10 mins and then fire another mail. But keep in mind the cron has to monitor the FS every minute. I am just trying to figure out how to stop a flood of mails to my inbox incase of issues, where 100s of files are generated every minute.

Once we get a mail, we will work on fixing the issue reported in the logs.

Here's my code

#!/bin/sh
fc=`find /opt/log/myapp/active/ -name *.LOG -mmin -1|wc -l`
send_mail (){
    [email protected]
    echo "$2" | /bin/mail -s "$1" $email
}
echo $fc
if [ $fc -gt 2 ]
then
emailSubject="Log files anamoly"
emailBody="The log files for your app is being written at a faster rate usual. No. of files written in the last minute are $fc"
send_mail "$emailSubject" "$emailBody"
fi

So, cron runs every minute and checks for logs generated in that minute. It should alert me when it crosses the threshold. Then, wait for 10 mins and then alert again if more logs are generated at the 11th minute. Please help.

Upvotes: 2

Views: 934

Answers (1)

Ewan Mellor
Ewan Mellor

Reputation: 6847

Try this:

sentMailLock=/var/cache/myapp/sentMail.lock
sendMail=false

if [ ! -e "$sentMailLock" ]
then
  sendMail=true
else
  old=$(find "$sentMailLock" -mmin +10)
  if [ -n "$old" ]
  then
    sendMail=true
  fi
fi

if $sendMail
then
  ...
  send_mail "$emailSubject" "$emailBody"
  touch "$sentMailLock"
fi

Upvotes: 4

Related Questions