2

its been a long time and I cant seem to remember how to do this. I am trying to grep a logfile for a word or words and email if it does not exist in the last fifteen minutes ( I will be setting a cron job every fifteen minutes unless there is a better way to do it) what I have so far is

if grep --quiet 'SEND OK' /logfile; then
  echo exists
else
  echo not found | mail -s "houston we have a problem" email@gmail.com
fi

can I use tail to check the logfile for the last 15 minutes? does |tail -15 do the trick?

and can I give it an "if" to email me if it doesnt find the keyword in the last 15 minutes as it will be run every fifteen minutes

I would greatly appreciate any help

Andrew Schulman
  • 8,811
  • 21
  • 32
  • 47
Brian
  • 21
  • 2
  • Maybe `logwatch` is what you want? The other suggestion I have is to structure your code so that it outputs nothing in the good case, and only output in the bad case and rely on cron's feature to only email detected output. – Colin 't Hart May 09 '15 at 17:40

2 Answers2

0

If you're trying to look at the last N minutes worth of the file (ar at least the contents of the file written since last time your script ran) then you need something like logtail (http://linux.die.net/man/8/logtail). This might already be available in your distribution. tail on its own won't help as it will only give you the last N lines/characters no matter when they were written.

Paul Haldane
  • 4,517
  • 1
  • 21
  • 32
0

If in your log you have date and time information (i think so), you can preponed to your grep another grep for filtering date and use -A {{ big_number }} to get all lines from 15 minutes ago to now.

Something similar to:

grep "$(date -d "15 minutes ago" +"{{your_log_date_format}}")" -A {{ big_number }} /logfile | grep --quiet 'SEND OK'

This is the dirty way (you can have problem if your {{ big_number }} is smallest than the rows written on the log in the last 15 minutes).

Credits goes to: http://geek.co.il/2010/04/08/script-day-output-the-tail-of-a-log-based-on-time.

lgaggini
  • 611
  • 4
  • 8