是否可以用bash比较包含日期的变量,格式为“ 2019-04-16T13:65:00.7567981Z”?

时间:2019-04-17 14:37:20

标签: bash rhel

我正在尝试比较bash中包含日期格式为“ 2019-04-16T13:657567981Z”的两个变量,并且我不确定bash是否可以识别日期格式,还是我必须先将其转换为字符串格式然后尝试进行比较?

我可以理解使用%s选项将其更改为可比较的整数格式的可能性,但是我的问题是bash不能识别这种格式吗?

#!/bin/sh

date1=`date -d "1 day ago" '+%Y-%m-%dT%H:%M:%S.%NZ'`
echo date1 = $date1

date2='2019-04-05T11:00Z'
echo "date2 = ${date2}"

ts2=`date -d"${date2}" '+%Y-%m-%dT%H:%M:%S.%NZ'`
echo "ts2 = ${ts2}"

ToBeDeleted=$ts2

if       [ "$date1" -gt "$ts2" ];       then
        ToBeDeleted=$date1
fi

if      [ "$date1" -lt "$ts2" ];       then
        ToBeDeleted=$ts2
fi

echo "Result = ${ToBeDeleted}"


RUNNING METHOD :
Saved the scipt in a bash script file in tmp and running using bash command
bash -x testscript2.sh


OUTPUT :
[root@RHEL74 tmp]# bash -x testscript2.sh
++ date -d '1 day ago' +%Y-%m-%dT%H:%M:%S.%NZ
+ date1=2019-04-16T14:01:40.510315383Z
+ date2=2019-04-05T11:00Z
++ date -d2019-04-05T11:00Z +%Y-%m-%dT%H:%MZ
+ ts2=2019-04-05T11:00Z
+ ToBeDeleted=2019-04-05T11:00Z
testscript2.sh: line 12: ToBeDeleted=2019-04-05T11:00Z: command not found
+ ' [[' 2019-04-16T14:01:40.510315383Z $'==\302\2402019-04-05T11:00Z' ']]'
testscript2.sh: line 14: $'\302\240[[': command not found
+ echo 'snapshot to be deleted = '
snapshot to be deleted =

转换为类似以下的格式

时也可以使用
#!/bin/sh

date1=`date -d "1 day ago" '+%Y-%m-%dT%H:%M:%S.%NZ'`
date11=`date -d"${date1}" +%Y%m%d%H%M%S`
echo date11 = $date11

date2='2019-04-05T11:00Z'

ts2=`date -d"${date2}" '+%Y-%m-%dT%H:%MZ'`
date22=`date -d "${ts2}" +%Y%m%d%H%M%S`
echo "date22 = ${date22}"

ToBeDeleted==$date22

if       [ "$date11" -gt "$date22" ];    then
       "$ToBeDeleted"="$date11"
fi

if       [ "$date11" -lt "$date22" ];    then
        "$ToBeDeleted"="$date22"
fi

echo "snapshot to be deleted = ${ToBeDeleted}"

输出:

[root@RHEL74 tmp]# bash testscript2.sh

date11 = 20190416142223

date22 = 20190405110000

testscript2.sh: line 15: $'\302\240[': command not found

snapshot to be deleted = =20190405110000

1 个答案:

答案 0 :(得分:0)

您必须将格式转换为更“可比”的格式。

您可以将日期转换为时间戳(总秒数)并进行比较。检查此帖子的第一个答案:https://unix.stackexchange.com/questions/84381/how-to-compare-two-dates-in-a-