Only read -r
is specified by POSIX; read -n NUM
, used to read NUM
characters, is not. Is there a portable way to automatically return after reading a given number of characters from stdin?
My usecase is printing prompts like this:
Do the thing? [y/n]
If possible, I'd like to have the program automatically proceed after typing y
or n
, without needing the user to press enter afterwards.
Best Answer
Reading one character means reading one byte at a time until you get a full character.
To read one byte with the POSIX toolchest, there's
dd bs=1 count=1
.Note however reading from a terminal device, when that device is in
icanon
mode (as it generally is by default), only ever returns when you press Return (a.k.a. Enter), because until then the terminal device driver implements a form of line editor that allows you to use Backspace or other editing characters to amend what you enter, and what you enter is made available to the reading application only when you submit that line you've been editing (with Return or Ctrl+D).For that reason,
ksh
'sread -n/N
orzsh
'sread -k
, when they detect stdin is a terminal device, put that device out of theicanon
mode, so that bytes are available to read as soon as they are sent by the terminal.Now note that
ksh
'sread -n n
only reads up ton
characters from a single line, it still stops when a newline character is read (use-N n
to readn
characters).bash
, contrary ksh93, still does IFS and backslash processing for both-n
and-N
.To mimic
zsh
'sread -k
orksh93
'sread -N1
orbash
'sIFS= read -rN 1
, that is, read one and only one character from stdin, POSIXly: