如何清除bash中的输入

Syl*_*ain 5 bash flush

我正在制作一个脚本,该脚本在任务后读取答案,然后将其写入文本文件中。我希望这个答案只是一个字符:

task1
read -n 1 answer < /dev/tty
echo $answer >> result.txt
task2
read -n 1 answer < /dev/tty
echo $answer >> result.txt
Run Code Online (Sandbox Code Playgroud)

问题是,如果我不小心按了两次键盘,第二个字符就会保留在内存中并将其写为下一个答案。

我想插入一个命令,在第一个字符写入 file.txt 后刷新内存,谢谢

Art*_*les 3

由于您不用于ENTER捕获答案,因此您需要设置延迟来识别什么是意外按下。因此,在读取第一个字符后,您可以使用read -e -t2放弃 2 秒内按下的任何按键。

task1
read -n 1 answer 
echo $answer >> result.txt
read -e -t2 #Discard additional input within 2 seconds.
task2
read -n 1 answer 
echo $answer >> result.txt
read -e -t2 #Discard additional input within 2 seconds.
Run Code Online (Sandbox Code Playgroud)