比较shell脚本中的两个日期 [英] Compare two dates in shell script

查看:89
本文介绍了比较shell脚本中的两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较存储在两个变量中的两个日期,格式为 YYYY-MM-DD .我想我可以将它们存储在另一个变量中,并使用一些 tr -d-" ,然后像整数一样进行比较,但是我不知道该怎么做.预先感谢!

I need to compare two dates which are stored in two variables, the format is YYYY-MM-DD . I suppose I can store them in another variables and use some tr -d "-",then compare like integers, but I don’t know how. Thanks in advance !

推荐答案

您可能需要调出 expr ,具体取决于您的神秘外壳:

You may need to call out to expr, depending on your mystery shell:

d1="2015-03-31" d2="2015-04-01"
if [ "$d1" = "$d2" ]; then
    echo "same day"
elif expr "$d1" "<" "$d2" >/dev/null; then
    echo "d1 is earlier than d2"
else
    echo "d1 is later than d2"
fi

d1 is earlier than d2


test 命令(或别名 [))仅实现字符串相等和不相等运算符.当您给(非bash)shell发出此命令时:


The test command (or it's alias [) only implements string equality and inequality operators. When you give the (non-bash) shell this command:

[ "$d1" > "$d2" ]

>"$ d2" 部分被视为stdout重定向.创建名为(在本例中)"2015-04-01"的零长度文件,条件命令变为

the > "$d2" part is treated as stdout redirection. A zero-length file named (in this case) "2015-04-01" is created, and the conditional command becomes

[ "$d1" ]

并且由于该变量为非空变量,因此评估为成功状态.

and as the variable is non-empty, that evaluates to a success status.

该文件的大小为零,因为 [命令没有标准输出.

The file is zero size because the [ command generates no standard output.

这篇关于比较shell脚本中的两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆