Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read 1 symbol in zsh?

Tags:

zsh

I need to get exactly one character from console and not print it. I've tried to use read -en 1 as I did using bash. But this doesn't work at all. And vared doesn't seem to have such option.

How to read 1 symbol in zsh? (I'm using zsh v.4.3.11 and v.5.0.2)

like image 897
roboslone Avatar asked Apr 27 '13 17:04

roboslone


3 Answers

read -sk

From the documentation:

-s

Don’t echo back characters if reading from the terminal. Currently does not work with the -q option.

-k [ num ]

Read only one (or num) characters. All are assigned to the first name, without word splitting. This flag is ignored when -q is present. Input is read from the terminal unless one of -u or -p is present. This option may also be used within zle widgets.

Note that despite the mnemonic ‘key’ this option does read full characters, which may consist of multiple bytes if the option MULTIBYTE is set.

like image 73
Alex Avatar answered Nov 11 '22 00:11

Alex


If you want your script to be a bit more portable you can do something like this:

y=$(bash -c "read -n 1 c; echo \$c")
like image 3
Bijou Trouvaille Avatar answered Nov 10 '22 23:11

Bijou Trouvaille


read reads from the terminal by default:

% date | read -sk1 "?Enter one char: "; echo $REPLY
Enter one char: X

Note above:

  • The output of date is discarded
  • The X is printed by the echo, not when the user enters it.

To read from a pipeline, use file descriptor 0:

% echo foobar | read -rk1 -u0; echo $REPLY
f
% echo $ZSH_VERSION
5.5.1
like image 3
Tom Hale Avatar answered Nov 10 '22 23:11

Tom Hale