微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 如何在指定的时间段内在bash脚本中运行命令?

比方说,只有当前时间是从上午11点10分到下午2点30分才能运行“命令”.如何在bash脚本中完成此操作?

下面用伪语言写的东西:

#!/bin/bash
while(1) {
    if ((currentTime > 11:10am) && (currentTime <2:30pm)) {
        run command;
        sleep 10;
    }
}

解决方法:

其他答案忽略了当一个数字从0开始时,Bash将在基数8†中解释它.因此,例如,当它是上午9点时,日期’%H%M’将返回0900,这是Bash中的无效数字. (不再).

一个适当而安全的解决方案,使用现代Bash:

while :; do
    current=$(date '+%H%M') || exit 1 # or whatever error handle
    (( current=(10#$current) )) # force bash to consider current in radix 10
    (( current > 1110 && current < 1430 )) && run command # || error_handle
    sleep 10
done

如果您接受第一次运行的潜在10秒延迟,可以缩短一点:

while sleep 10; do
    current=$(date '+%H%M') || exit 1 # or whatever error handle
    (( current=(10#$current) )) # force bash to consider current in radix 10
    (( current > 1110 && current < 1430 )) && run command # || error_handle
done

完成!

†看:

$current=0900
$if [[ $current -gt 1000 ]]; then echo "does it work?"; fi
bash: [[: 0900: value too great for base (error token is "0900")
$# oooops
$(( current=(10#$current) ))
$echo "$current"
900
$# good :)

正如xsc在评论中指出的那样,它适用于古代[内置…但这已成为过去:).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐