Bash:如何通过按下任意键来结束无限循环? [英] Bash: How to end infinite loop with any key pressed?

查看:25
本文介绍了Bash:如何通过按下任意键来结束无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个无限循环,当按下任意键时停止.

I need to write an infinite loop that stops when any key is pressed.

不幸的是,这个只有在按下一个键时才会循环.

Unfortunately this one loops only when a key is pressed.

有想法吗?

#!/bin/bash

count=0
while : ; do

    # dummy action
    echo -n "$a "
    let "a+=1"

    # detect any key  press
    read -n 1 keypress
    echo $keypress

done
echo "Thanks for using this script."
exit 0

推荐答案

您需要将标准输入置于非阻塞模式.这是一个有效的例子:

You need to put the standard input in non-blocking mode. Here is an example that works:

#!/bin/bash

if [ -t 0 ]; then
  SAVED_STTY="`stty --save`"
  stty -echo -icanon -icrnl time 0 min 0
fi

count=0
keypress=''
while [ "x$keypress" = "x" ]; do
  let count+=1
  echo -ne $count'
'
  keypress="`cat -v`"
done

if [ -t 0 ]; then stty "$SAVED_STTY"; fi

echo "You pressed '$keypress' after $count loop iterations"
echo "Thanks for using this script."
exit 0

编辑 2014/12/09:-icrnl 标志添加到 stty 以正确捕获 Return 键,使用 cat-v 而不是 read 以捕获空间.

Edit 2014/12/09: Add the -icrnl flag to stty to properly catch the Return key, use cat -v instead of read in order to catch Space.

如果输入的数据足够快,cat 可能会读取多个字符;如果不是所需的行为,请将 cat -v 替换为 dd bs=1 count=1 status=none |cat -v.

It is possible that cat reads more than one character if it is fed data fast enough; if not the desired behaviour, replace cat -v with dd bs=1 count=1 status=none | cat -v.

编辑 2019/09/05: 使用 stty --save 恢复 TTY 设置.

Edit 2019/09/05: Use stty --save to restore the TTY settings.

这篇关于Bash:如何通过按下任意键来结束无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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