比方说,只有当前时间是从上午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在评论中指出的那样,它适用于古代[内置…但这已成为过去:).
标签:bash,linux
来源: https://codeday.me/bug/20190725/1532572.html