Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Best Way to Perform Timestamp Comparison in Bash

Tags:

bash

time

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?

like image 616
Ichorus Avatar asked Oct 15 '08 17:10

Ichorus


People also ask

How do I compare two timestamps in Unix?

If so, you can lexicographically compare your timestamp with the output of date -u -d '-10 minutes' +%Y%m%d%H%M%S (the -u assumes that your database timestamp is in UTC, which I'd advise).

How do I compare two dates in Shell?

You can use date +%s -d your_date to get the number of seconds since a fixed instance (1970-01-01, 00:00 UTC) called "epoch". Once you get that it's really easy to do almost anything with dates.

How do bash scripts work?

A bash script is a series of commands written in a file. These are read and executed by the bash program. The program executes line by line. For example, you can navigate to a certain path, create a folder and spawn a process inside it using the command line.


1 Answers

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 
like image 98
Bruno De Fraine Avatar answered Sep 21 '22 01:09

Bruno De Fraine