tags:

views:

3363

answers:

3

I have an alert script that I am trying to keep from spamming me so I'd like to place a condition that if an alert has been sent within, say the last hour, to not send another alert. Now I have a cron job that checks the condition every minute because I need to be alerted quickly when the condition is met but I don't need to get the email every munite until I get the issue under control. What is the best way to compare time in bash to accomplish this?

+4  A: 

Use "test":

if test file1 -nt file2; then
   # file1 is newer than file2
fi

EDIT: If you want to know when an event occurred, you can use "touch" to create a file which you can later compare using "test".

JesperE
Thanks, I was not aware of the -nt bit. I could create a file when the alert is first tripped and delete it when the condition recovers (In that case I could just check for existence). Any idea how I could implement the 'if it has been at least an hour throw the alert again' bit?
Ichorus
I believe @Bruno answered that.
JesperE
+2  A: 
jonathan-stafford
Why not just use seconds since the epoch (%s)? 3600 seconds in an hour.
Steve Baker
Because although I thought that option existed, I kept overlooking it...
jonathan-stafford
+9  A: 

By far the easiest is to store time stamps as modification times of dummy files. GNU touch and date commands can set/get these times and perform date calculations. Bash has tests to check whether a file is newer than (-nt) or older than (-ot) another.

For example, to only send a notification if the last notification was more than an hour ago:

touch -d '-1 hour' limit
if [ limit -nt last_notification ]; then
    #send notification...
    touch last_notification
fi
Bruno De Fraine