bash only email if occurrence since last alert

我们两清 提交于 2019-12-31 05:36:47

问题


I'm monitoring a log file for a specific word and using tac to output the 5 lines before and after it

#!/bin/bash
tac /var/log/syslog |grep -m1 -A5 -B5 'WORD' | tac >> /tmp/systemp
mailx email commands  
rm /tmp/systemp

and I've setup a cron to run every 5 minutes however as expected I receive duplicate alert emails, how do I make it send an email for the last occurrence and not again until the next one?

ie

Feb 27 15:05:39 WORD (email)
Cron runs again after 5 minutes
Feb 27 15:05:39 WORD (don't email)
Cron runs again after 5 minutes 
Feb 27 15:35:39 WORD (email)

回答1:


You should only search trough last 5 min of data:

data5m=$(awk '$0>=from' from="$(date +"%b %e %H:%M:%S" -d -5min)" /var/log/syslog)

Then you can grep from this data:

grep -m1 -C5 'WORD' <<< "$data5m"

Update:

awk '$0>=from' from="$(date +"%b %e %H:%M:%S" -d -5min)" /var/log/syslog | grep -m1 -C5 'WORD'

Or all in one awk

awk '{a[NR]=$0} /pattern/ && $0>=from {f=NR} END {for (i=f-5;i<=f+5;i++) print a[i]}' from="$(date +"%b %e %H:%M:%S" -d -5min)" /var/log/syslog


来源:https://stackoverflow.com/questions/28815293/bash-only-email-if-occurrence-since-last-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!