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)
Posted by Stu | February 10, 2008 4:02 AM
Posted on February 10, 2008 04:02