Bash:检索和比较两个date

在Bash脚本中,我想比较两个date,如果一个大于另一个,则执行一个任务。

我比较的两个date是:

svn回购的最后更改date,我得到如下date信息:

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

它给了我这样的东西:

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

然后我find目录中最新的备份文件的date信息,如下所示:

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

(我不知道有没有更好的方法来做到这一点,无论是头部和尾部以上)

这给了我这样的东西:

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

接下来我要做的是从第一个输出中检索date,并将其与第二个输出date进行比较,如果其中一个大于另一个,我将执行一个svn转储。 什么是最合适的方式来做到这一点?

谢谢。

/ bin / date可以将时间转换为格式,包括从纪元开始的秒数。

 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 
 ## Specify the filename to dump here _filename = svn.dump ## Grab the mtime of the file and print out in "seconds since Epoch format" _fileepoch=$(find ${_filename} -printf "%Ts") ## Grab the last changed date of the file and store it in _svndate _svndate=$(svn info svn://server.com/reponame -r 'HEAD' \ | grep 'Last Changed Date' \ | awk '{print $4, $5, $6}') ## Use date --date with the "%s" format specifier to print seconds since Epoch ## for that date _svnepoch=$(date --date "${_svndate}" "+%s") 

你现在应该可以比较${_svnepoch}${_fileepoch}

我只是简单地比较一下从历元ls -lt --time-style="+%s"的秒数。 这给你一个很好的数字,你可以比较。

man bash

  arg1 OP arg2 OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers. 

容易做到。

 F1=$(ls -l --time-style='+%s' file1|awk '{ print $6 }') F2=$(ls -l --time-style='+%s' file2|awk '{ print $6 }') if [ $F1 -gt $F2 ]; then echo yay echo F1: $F1 else echo nay echo F2: $F2 fi 

正如其他人所说的,一个实际赋予date含义的脚本语言可能更适合这类任务