Bash 将字符串转换为日期并与文件创建时间进行比较

Bash 将字符串转换为日期并与文件创建时间进行比较,bash,date,Bash,Date,我试图在bash中比较转换为日期的字符串和文件创建时间 #!/bin/bash test='2020-05-13 08:00' testConverted=$(date -d "$test" +'%Y %m %d %H:%M') [ "~/fileToCompare" -nt "$testConverted" ] && echo "yes" 无论我放在哪个测试日期,它总是返回false。日期转换错误吗?可以这样做吗?方法是使用date命令将日期字符串转换为Unix历元时间(自

我试图在bash中比较转换为日期的字符串和文件创建时间

#!/bin/bash

test='2020-05-13 08:00'
testConverted=$(date -d "$test" +'%Y %m %d %H:%M')
[ "~/fileToCompare" -nt "$testConverted" ] && echo "yes"

无论我放在哪个测试日期,它总是返回false。日期转换错误吗?可以这样做吗?

方法是使用
date
命令将日期字符串转换为Unix历元时间(自1970年1月1日起的秒数),然后使用
stat
命令类似地获得测试文件的历元时间修改日期,并使用算术计算进行比较

#!bin/bash

testDate='2020-05-13 08:00'
testFile="$HOME/fileToCompare"

if (( $(date -d "$test" +%s) > $(stat "$testFile" -c %Z) )); then
  echo "testDate ($testDate) is newer than $testFile"
fi

波浪号
~
不会以引号展开,请尝试使用
$HOME
代替。谢谢,无论我输入什么日期,它现在都会返回“true”。