在 Bash 中执行时间戳比较的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/205666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the Best Way to Perform Timestamp Comparison in Bash
提问by Ichorus
I have an alert script that I am trying to keep from spamming me so I'd like to place a condition that if an alert has been sent within, say the last hour, to not send another alert. Now I have a cron job that checks the condition every minute because I need to be alerted quickly when the condition is met but I don't need to get the email every munite until I get the issue under control. What is the best way to compare time in bash to accomplish this?
我有一个警报脚本,我试图防止向我发送垃圾邮件,所以我想设置一个条件,如果警报已在例如最后一小时内发送,则不发送另一个警报。现在我有一个 cron 作业,每分钟检查一次条件,因为我需要在满足条件时迅速收到警报,但在我控制问题之前,我不需要每个 munite 都收到电子邮件。在 bash 中比较时间以实现这一目标的最佳方法是什么?
回答by Bruno De Fraine
By far the easiest is to store time stamps as modification times of dummy files. GNU touch
and date
commands can set/get these times and perform date calculations. Bash has tests to check whether a file is newer than (-nt
) or older than (-ot
) another.
到目前为止,最简单的方法是将时间戳存储为虚拟文件的修改时间。GNUtouch
和date
命令可以设置/获取这些时间并执行日期计算。Bash 有测试来检查一个文件是比 ( -nt
)新还是比 ( ) 旧-ot
。
For example, to only send a notification if the last notification was more than an hour ago:
例如,仅在最后一个通知是一个多小时之前发送通知:
touch -d '-1 hour' limit
if [ limit -nt last_notification ]; then
#send notification...
touch last_notification
fi
回答by JesperE
Use "test":
使用“测试”:
if test file1 -nt file2; then
# file1 is newer than file2
fi
EDIT: If you want to know when an event occurred, you can use "touch" to create a file which you can later compare using "test".
编辑:如果您想知道事件发生的时间,可以使用“touch”创建一个文件,稍后您可以使用“test”进行比较。
回答by jonathan-stafford
Use the date command to convert the two times into a standard format, and subtract them. You'll probably want to store the previous execution time in a dotfile then do something like:
使用 date 命令将两个时间转换为标准格式,然后将它们相减。您可能希望将先前的执行时间存储在 dotfile 中,然后执行以下操作:
last = cat /tmp/.lastrun
curr = date '+%s'
diff = $(($curr - $last))
if [ $diff -gt 3600 ]; then
# ...
fi
echo "$curr" >/tmp/.lastrun
(Thanks, Steve.)
(谢谢,史蒂夫。)