bash 如果时间大于 X 小于 Y,在黎明之间?

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

If time is more than X and less than Y, between daybreaks?

bashdateif-statementtime

提问by Paolo

In one of my loops, I've made my Bash script do things depending on the time:

在我的一个循环中,我让我的 Bash 脚本根据时间做一些事情:

if [ $(date +%k%M) -ge 2200 ] && [ $(date +%k%M) -lt 2300 ] ; then echo "Betwen 22 and 23!"; fi

However, I just got a problem I didn't expect (although I should have). The if doesn't work when 23:59 becomes 00:00.

但是,我遇到了一个我没想到的问题(虽然我应该有)。当 23:59 变为 00:00 时,if 不起作用。

if [ $(date +%k%M) -ge 2359 ] && [ $(date +%k%M) -lt 200 ] ; then CURRENTFOLDER="$TARGETFOLDER/$BLOCK1"; fi 

200 is numerically less than 2359, but 02:00 is later than 23:59.

200 在数值上小于 2359,但 02:00 晚于 23:59。

What can I do?

我能做什么?

回答by das.cyklone

Converting to seconds makes this type of 'arithmetic' much easier and more reliable. Use date's '--date=' option to specify that next day's window:

转换为秒使这种类型的“算术”更容易、更可靠。使用 date 的 '--date=' 选项指定第二天的窗口:

date --date="Today HH:MM" +"%s"
date --date="+1 day HH:MM" +"%s"

Also, for simplicity's sake, call the current time once and use it for comparison :)

另外,为简单起见,调用一次当前时间并将其用于比较:)

NOW=$(date +"%s")

Examples:

例子:

(( ${NOW} >= $(date --date="Today 22:00" +"%s") )) && (( ${NOW} < $(date --date="Today 23:00" +"%s") ))

(( ${NOW} >= $(date --date="Today 23:59" +"%s") )) && (( ${NOW} < $(date --date="+1 day 02:00" +"%s") ))

You can also use seconds field to do file modification comparisons, etc., using output from 'find' or 'stat'.

您还可以使用 seconds 字段进行文件修改比较等,使用来自“find”或“stat”的输出。

Depending on how many actions you take, you'd be better using combining into a case statement.

根据您采取的操作数量,最好使用组合到 case 语句中。

Good luck.

祝你好运。