Bash脚本倒计时器需要检测任何键才能继续

前端之家收集整理的这篇文章主要介绍了Bash脚本倒计时器需要检测任何键才能继续前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在倒数计时器循环中收听任何按键.如果按下任何键,倒计时器应该突破它的循环.这主要是有效的,除了输入键只是让倒数计时器更快.
#!/bin/bash
for (( i=30; i>0; i--)); do
    printf "\rStarting script in $i seconds.  Hit any key to continue."
    read -s -n 1 -t 1 key
    if [[ $key ]]
    then
        break
    fi
done
echo "Resume script"

我似乎无法找到任何在线任何位置检测输入密钥的示例.

我认为基于读取的返回代码,可以解决这个问题.从阅读的手册页,
The return code is zero,unless end-of-file is encountered,read times out,or an invalid file descriptor is supplied as the argument to -u.

超时的返回码似乎是142 [在Fedora 16中验证]

所以,脚本可以修改为,

#!/bin/bash
for (( i=30; i>0; i--)); do
    printf "\rStarting script in $i seconds.  Hit any key to continue."
    read -s -n 1 -t 1 key
    if [ $? -eq 0 ]
    then
        break
    fi
done
echo "Resume script"
原文链接:https://www.f2er.com/bash/387085.html

猜你在找的Bash相关文章