9

I can get read -n 1 KEY to get most keys, except for keys which are represented by multiple characters. For example, if I press the up arrow key:

$ read -n 1; echo
^[[A
$ [A

As you can see, read only takes the Esc and the [A is left over.

What I want to be able to do in a script is:

  1. Go through a list with the arrow keys and press Enter to do something with it
  2. For other actions, press different keys.
biggles5107
  • 287
  • 2
  • 4
  • 10
  • Ncurses is a library to make such console interfaces: http://stackoverflow.com/questions/7876008/what-ncurses-frameworks-are-available-for-bash – Rafał Rawicki Jul 21 '12 at 21:45

2 Answers2

10

You are better off using dialog as jm666 mentioned, but there are other ways to skin that cat.

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.

Warning, fast typists could get annoyed. You might need to tweak that timeout.

Seth Robertson
  • 30,608
  • 7
  • 64
  • 57
  • 2
    @bi99l35: I guess 2400 baud dialup connections are pretty rare, so that should be safe. – Seth Robertson Jul 22 '12 at 22:55
  • Still not good when you copy&paste some text. Then no timeout is fast enough to detect this. We should use the terminfo to find out whether we have a multibyte keypress at hand. – Alfe Sep 06 '13 at 10:34
  • This doesn't work for me (linux) when the character is Enter or Space or Tab. It does work for Backspace and even Esc, though. – dylnmc Nov 17 '14 at 20:09
5

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/

Google form some examples, or check: http://unstableme.blogspot.sk/2009/12/linux-dialog-utility-short-tutorial.html

clt60
  • 62,119
  • 17
  • 107
  • 194