Comparing dates in shell scripts


In writing shell scripts that parse log files, it sometimes, perhaps often, would be useful to be able to programmatically look at the date for a given entry and act upon it based on that date/time. It is possible to do this to a degree using the date command. Note that, at the time of this writing, this only works with the GNU date utility, meaning it will work on any Linux distro, or you can download and compile GNU's date utility for your respective Unix platform.

The key is the -d parameter for the date command. With it, you can give the date in, say, '21 Dec 2007 12:14:56' format, and it will give you the date with those dates & times, and you can then adjust the format with the usual switches. For example

date -d '21 Oct 2006 02:43:13' +%s
will display 1161416593 which is the number of seconds from the epoch to the date/time given.

This script will take a date in various formats and tell you whether it is more than 15 minutes old or not. It's not very useful by itself, but it shows the code that you can adapt for your own purposes.

recsecs=$(date -d "$1" +%s)
cutoff=$(date -d "-15 minutes" +%s)
if [ $recsecs -lt $cutoff ]; then
        echo "Too old"
else
        echo "Time is within range"
fi

12/26/2007