如何在 Bash 中读取任意一个键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11596059/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I read any one key in Bash?
提问by biggles5107
I can get read -n 1 KEYto get most keys, except for keys which are represented by multiple characters. For example, if I press the up arrow key:
我read -n 1 KEY可以获得大多数键,除了由多个字符表示的键。例如,如果我按向上箭头键:
$ read -n 1; echo
^[[A
$ [A
As you can see, readonly takes the Escand the [Ais left over.
如您所见,read只需要Esc和[A剩下的。
What I want to be able to do in a script is:
我希望能够在脚本中做的是:
- Go through a list with the arrow keys and press Enterto do something with it
 - For other actions, press different keys.
 
- 使用箭头键浏览一个列表,然后按Enter它来做一些事情
 - 对于其他操作,请按不同的键。
 
回答by Seth Robertson
You are better off using dialog as jm666 mentioned, but there are other ways to skin that cat.
您最好使用 jm666 提到的对话框,但还有其他方法可以给那只猫剥皮。
read -n 1 x; while read -n 1 -t .1 y; do x="$x$y"; done
Basically wait until you read a character and then spin consuming input until .1 seconds has passed w/o input.
基本上等到你读到一个字符,然后旋转消耗输入,直到 0.1 秒过去了没有输入。
Warning, fast typists could get annoyed. You might need to tweak that timeout.
警告,快速打字员可能会生气。您可能需要调整该超时。
回答by jm666
Not a direct answer to your question - but the way of solution:
不是直接回答您的问题-而是解决方法:
You probably should check the "dialog" utility for creating "ncurses" (screen oriented) dialog boxes from the shell. see: http://hightek.org/dialog/
您可能应该检查“对话框”实用程序以从外壳创建“ncurses”(面向屏幕)对话框。见:http: //hightek.org/dialog/
Google form some examples, or check: http://unstableme.blogspot.sk/2009/12/linux-dialog-utility-short-tutorial.html
谷歌形成一些例子,或检查:http: //unstableme.blogspot.sk/2009/12/linux-dialog-utility-short-tutorial.html

