Bash脚本倒计时需要检测任何键才能继续
我需要在倒计时循环中监听任何按键。如果按下任何键,则倒计时计时器应中断其循环。这主要起作用,除了回车键使倒计时时间加快Bash脚本倒计时需要检测任何键才能继续,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 d
#!/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"
<>我似乎找不到任何例子来检测在线上的任何输入键。< /P> < P>问题是,<代码> Read < /Cord>默认情况下,将换行符作为定界符。 将
IFS
设置为null,以避免读取到分隔符
说:
相反,在
read
过程中按Enter键时,您会得到预期的行为。我认为,根据read
的返回代码,可以解决此问题。从的man
页面读取
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"
不幸的是,这导致了与我相同的行为。回车键只会继续到下一个循环迭代。我一直在寻找与你类似的解决方案,但从未找到。
#!/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"