Bash: Retrieving and comparing two dates

bash

In Bash script, I would like to compare two dates and if one is greater than the other, carry out a task.

Two dates that I'm comparing are:

svn repo's last change date, I get the date info like so:

svn info svn://server.com/reponame -r 'HEAD' | grep 'Last Changed Date'

It gives me something like this:

Last Changed Date: 2011-06-06 22:26:50 -0400 (Mon, 06 Jun 2011)

Then I'm finding the date information of the most current backup file in the directory, like so:

ls -lt --time-style="+%Y-%m-%d %H:%M:%S" | head -n 2 | tail -n 1

(I wonder if there is a better way to do it with out both head and tail above)

Which gives me something like this:

-rw-r--r-- 1 user1 user1 14 2011-06-09 07:52:50 svn.dump

What I would like to do next, is to retrieve date from first output and compare it with second output date and if one is greater than the other one, I will do an svn dump. what would be the most appropriate way to do this?

Thanks.

Best Answer

/bin/date can convert time to formats, including seconds from epoch.

DATE_1="`svn info svn://server.com/reponame -r 'HEAD' | grep 'Last Changed Date' | grep -E -o \"[0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}\"`"

DATE_2="`ls -lt --time-style="+%Y-%m-%d %H:%M:%S" | head -n 2 | tail -n 1 | grep -E -o \"[0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}\"`"

if [ "`date --date \"$DATE_1\" +%s`" -gt "`date --date \"$DATE_2\" +%s`" ]; then
    echo "Greater"
else
    echo "Less or equal"
fi