Bash脚本倒数计时器需要检测任何键才能继续 [英] Bash script countdown timer needs to detect any key to continue

查看:88
本文介绍了Bash脚本倒数计时器需要检测任何键才能继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要监听倒数计时器循环中的任何按键.如果按下任何键,则倒数计时器应退出其循环.除回车键只是使倒数计时器走得更快以外,这通常可以工作.

I need to listen for any key press in a countdown timer loop. If any key is pressed then the countdown timer should break out of it's loop. This mostly works except for the enter key just makes the countdown timer go faster.

#!/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"

我似乎找不到在线如何检测输入密钥的任何示例.

I just can't seem to find any examples of how to detect that enter key anywhere online.

推荐答案

我认为基于read的返回码,可以解决此问题.在readman页面上,

I think based on the return code of read, there is a work around for this problem. From the man page of 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.

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

The return code for timeout seems to be 142 [verified in 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"

这篇关于Bash脚本倒数计时器需要检测任何键才能继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆