击:如何结束与任何键的pressed无限循环? [英] Bash: How to end infinite loop with any key pressed?

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

问题描述

我需要在任何关键是pressed写一个无限循环的停止。

不幸的是这一个循环,只有当一个关键是pressed。

想法,请?

 #!/斌/庆典数= 0
而:;做#假动作
回声-n$ A
让A + = 1#检测到任何键preSS
读-n 1键preSS
回声$关键preSSDONE
回声感谢您使用这个脚本。
退出0


解决方案

您需要把标准输入非阻塞模式。这里是工作的一个例子:

 #!/斌/庆典如果[-t 0];随后的stty -echo -icanon -icrnl时0分0;科幻数= 0
关键preSS =''
而[X $关键preSS=X];做
  让数+ = 1
  回声-ne $计数'\\ r'
  关键preSS ='猫-v`
DONE如果[-t 0];然后stty的理智;科幻回声你$ P $ $计数循环迭代后pssed'$关键preSS'
回声感谢您使用这个脚本。
退出0

修改2014年12月9日: -icrnl 标记添加到的stty 去适当地捕捉回车键,使用猫-v 而不是为了赶空间。

这是可能的,如果它被送到数据不够快读取多个字符;如果不期望的行为,将猫-v DD BS = 1数= 1状态=无|猫-v

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

Unfortunately this one loops only when a key is pressed.

Ideas please?

#!/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 stty -echo -icanon -icrnl time 0 min 0; fi

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

if [ -t 0 ]; then stty sane; fi

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

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.

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.

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

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