What is the Best Way to Perform Timestamp Comparison in Bash What is the Best Way to Perform Timestamp Comparison in Bash bash bash

What is the Best Way to Perform Timestamp Comparison in Bash


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' limitif [ limit -nt last_notification ]; then    #send notification...    touch last_notificationfi


Use "test":

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

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".


Use the date command to convert the two times into a standard format, and subtract them. You'll probably want to store the previous execution time in a dotfile then do something like:

last = cat /tmp/.lastruncurr = date '+%s'diff = $(($curr - $last))if [ $diff -gt 3600 ]; then    # ...fiecho "$curr" >/tmp/.lastrun

(Thanks, Steve.)