Contribution: Checking for single Key press with Busybox ash

Rich Felker dalias at
Sun Jul 14 15:38:57 UTC 2013

On Sun, Jul 14, 2013 at 01:25:52AM +0200, Harald Becker wrote:
> Hi Denys !
> On 14-07-2013 00:54 Denys Vlasenko <vda.linux at>
> wrote:
> >"read -r -t2 -n1 KEY" ?
> >
> >The downside is that -tSECONDS -nMAXLEN are extensions,
> >not a standard.
> I know about this -t Extension, but never see -nMAXLEN ... beside
> it's none conformance, dos -nMAX mean that read does not wait
> until new line is pressed? I thought read always wait for a NL
> char before it returns any data entered into the variable.

Waiting for a newline is a function of the terminal mode, not the read
command. The default terminal mode buffers input at the kernel level
and _nothing_ appears on the file descriptor until a newline is
entered. In this case, the read command will still only consume one
byte the rest will remain unread on the terminal device.

In order to read units of data smaller than a line from a terminal,
you need to change the terminal mode with the stty command (and change
it back once you're done). I believe "canonical mode" (ICANON) is the
main thing you want to change, but there may be some other modes that
need changing too.

> The idea behind my example is to have the possibility to check
> for single key presses on every kind of tty and to catch even
> special function key presses witch produce multi character
> sequences. What about read when special control codes are
> entered? How do you check for them in a shell script?

If the first byte you read is an escape, you'd read more bytes until
you've read a whole key code. You may want a timeout in case the user
just manually pressed the escape key with nothing after it.


More information about the busybox mailing list