how to clear input in bash

Viewed 3101

I am making a script which read an answer after a task and then write it in a textfile. I want this answer to be just one character :

task1
read -n 1 answer < /dev/tty
echo $answer >> result.txt
task2
read -n 1 answer < /dev/tty
echo $answer >> result.txt

Problem is, if I accidently press twice the keyboard, the 2nd character remains in the memory and write it as the next answer.

I'd like to insert a command which flush the memory after the first character is written in file.txt thanks

4 Answers

This will do what you want:

{
  original_terminal_state="$(stty -g)"
  stty -icanon -echo min 0 time 0
  LC_ALL=C dd bs=1 > /dev/null 2>&1
  stty "$original_terminal_state"
} < /dev/tty
Related