如何让 bash 脚本循环到特定时间

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

How to have a bash script loop until a specific time

bashloopstime

提问by user788171

Usually to run an infinite bash loop, I do something like the following:

通常要运行无限 bash 循环,我会执行以下操作:

while true; do
    echo test
    sleep 1
done

What if instead, I want to do a loop that loops infinitely as long as it is earlier than 20:00. Is there a way to do this in bash?

如果相反,我想做一个无限循环的循环,只要它早于 20:00,该怎么办。有没有办法在 bash 中做到这一点?

回答by fedorqui 'SO stop harming'

You can use dateto print the hours and then compare to the one you are looking for:

您可以使用date打印小时数,然后与您要查找的小时数进行比较:

while [ $(date "+%H") -lt 20 ]; do
    echo "test"
    sleep 1
done

as date "+%H"shows the current hour, it keeps checking if we are already there or in a "smaller" hour.

date "+%H"当前小时所示,它会不断检查我们是否已经在那里或在“较小”的小时内。

回答by choroba

Just change trueto the real condition:

只需更改true为实际情况:

while (( $(date +%H) < 20 )) ; do
    echo Still not 8pm.
    sleep 1
done

回答by mxmlnkn

If you want a specific date, not only full hours, then try comparing the Unix time:

如果您想要一个特定的日期,而不仅仅是完整的小时数,那么请尝试比较 Unix 时间:

while [ $(date +%s) -lt $(date --date="2016-11-04T20:00:00" +%s) ]; do
    echo test
    sleep 1
done