我需要在倒数计时器循环中收听任何按键.如果按下任何键,则倒数计时器应该突破它的循环.这主要是有效的,除了输入键只是让倒数计时器更快.
#!/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"
Run Code Online (Sandbox Code Playgroud)
我似乎无法找到任何在线任何位置检测输入密钥的示例.
我认为根据返回代码read,有一个解决这个问题的方法.从man页面read,
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.
Run Code Online (Sandbox Code Playgroud)
超时的返回码似乎是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"
Run Code Online (Sandbox Code Playgroud)