« Awesome Error Message of the Day | Main | File Attributes in Linux »

Yet Another Reason I Love Linux

Problem: I need to be able to take a date/timestamp strings off of logged error messages and tell whether or not that time was within the last two hours. The strings are all formatted like this:

2007-10-10 09:30:13

The tricky part immediately became what to do when it's 1am and the date string shows 11:30pm on the previous day. What if it's January 1st, 2008 now and the error is from December 31st? This is a tiny project, so I don't feel like writing a function to compare times and take dates/months/years/leap years into account. Luckily, Linux saves the day once again with an awesome built-in function to convert date/time strings into Unix time.

Solution:

# Let's say we've already determined $ERROR_STRING is "2007-10-10 09:30:13"
CUR_TIME=`date +%s`
ERROR_TIME=`date -d "$ERROR_STRING" +%s`
if [ $ERROR_TIME -gt $CUR_TIME ]
then
     echo "ERROR: ERROR_TIME is in the future!"
     exit 1
fi
TIME_DIFF=$(($CUR_TIME - $ERROR_TIME))
if [ $TIME_DIFF -le 7200 ]
then
     echo "ERROR: Error occurred in the last two hours"
     exit 1
else
     echo "OK: Error is more than two hours old
     exit 0
fi

<3 <3 <3 Linux

Comments (1)

Stu:

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on October 10, 2007 12:07 PM.

The previous post in this blog was Awesome Error Message of the Day.

The next post in this blog is File Attributes in Linux.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.34