问题
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