bash 使用 date 命令比较时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2899110/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:17:55  来源:igfitidea点击:

Compare time using date command

linuxbashdatescripting

提问by vehomzzz

Say I want a certain block of a bash script executed only if it is between 8 am (8:00) and 5 pm (17:00), and do nothing otherwise. The script is running continuously.

假设我希望某个 bash 脚本块仅在上午 8 点 (8:00) 和下午 5 点 (17:00) 之间执行,否则不执行任何操作。脚本一直在运行。

So far I am using the datecommand.

到目前为止,我正在使用该date命令。

How to use it to compare it to the time range?

如何使用它与时间范围进行比较?

回答by Cascabel

Just check if the current hour of the day is between 8 and 5 - since you're using round numbers, you don't even have to muck around with minutes:

只需检查一天中的当前小时是否在 8 到 5 之间 - 由于您使用的是整数,因此您甚至不必纠结于分钟:

hour=$(date +%H)
if [ "$hour" -lt 17 -a "$hour" -ge 8 ]; then
    # do stuff
fi

Of course, this is true at 8:00:00 but false at 5:00:00; hopefully that's not a big deal.

当然,这在 8:00:00 为真,但在 5:00:00 为假;希望这不是什么大不了的事。

For more complex time ranges, an easier approach might be to convert back to unix time where you can compare more easily:

对于更复杂的时间范围,更简单的方法可能是转换回 unix 时间,以便您可以更轻松地进行比较:

begin=$(date --date="8:00" +%s)
end=$(date --date="17:00" +%s)
now=$(date +%s)
# if you want to use a given time instead of the current time, use
# $(date --date=$some_time +%s)

if [ "$begin" -le "$now" -a "$now" -le "$end" ]; then
    # do stuff
fi

Of course, I have made the mistake of answering the question as asked. As seamus suggests, you could just use a cron job - it could start the service at 8 and take it down at 5, or just run it at the expected times between.

当然,我犯了错误地回答问题。正如 seamus 所建议的那样,您可以只使用 cron 作业 - 它可以在 8 点启动服务并在 5 点关闭它,或者只是在预期的时间间隔运行它。

回答by seamus

Why not just use a cron job?

为什么不直接使用 cron 作业?

Otherwise

除此以外

if [[ `date +%H` -ge 8 && `date +%H` -lt 17 ]];then
    do_stuff()
fi

will do the job

会做这份工作