Bash – Reading char-by-char silently does not work

bashreadterminalterminal-emulator

I'm trying to read user input char by char, silently, as follows:

while [ 1 ]; do
  read -s -N 1
  ...
done

While this loop works perfectly using VNC (xterm), it works only partially using putty (xterm) or a Linux terminal, and most of other text terminals.

The problem is encountered when I become "wild" with the keyboard and striking multiple keys at the same time, and than some of the keys are echoed despite of the -s mode.

I've also tried to redirect output and stty -echo. while the first did not make any difference, the latter would be somehow helpful, minimizing the "echo"s to be less frequent, but not perfect.

Any Ideas?

Best Answer

read -s disables the terminal echo only for the duration of that read command. So if you type something in between two read commands, the terminal driver will echo it back.

You should disable echo and then call read in your loop without -s:

if [ -t 0 ]; then
  saved=$(stty -g)
  stty -echo
fi
while read -rN1; do
  ...
done
if [ -t 0 ]; then
  stty "$saved"
fi
Related Question