How to suppress echo of buggy read function

I’m trying to capture a key press in a shell script (e.g. using read) and not to echo it. The three methods I found were stty -echo, the -s switch and stream redirection.

However, on macOS, which seems to use a FreeBSD implementation, none of these work consistently.

The following script shows the issue:

while true; do
    stty -echo
    read -s -n 1 CHAR &>/dev/null
    stty echo
done

When pressing the up and down arrows at the same time, sometimes the command echoes A^[[B or B^[[A. This occurs particularly often when the machine is slow (due to low battery), indicating some race condition.

Am I missing something? Otherwise, how can I work around this issue?

Answer

In your loop, there is a short window of time between the “stty echo” at the end of the loop and the “stty -echo” at the next iteration. Keyboard input received during this window will be echoed, even though no read command is waiting for it. If you don’t want echoes, don’t call “stty echo” 😉

Leave a Reply

Your email address will not be published. Required fields are marked *