Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read any one key in Bash?

Tags:

bash

keyboard

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.
like image 948
biggles5107 Avatar asked Jul 21 '12 21:07

biggles5107


2 Answers

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.

like image 168
Seth Robertson Avatar answered Nov 06 '22 23:11

Seth Robertson


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

like image 32
jm666 Avatar answered Nov 06 '22 23:11

jm666