我正在编写一个脚本,在任务之后读取答案,然后将其写入文本文件中。我希望这个答案只是一个字符:
task1
read -n 1 answer < /dev/tty
echo $answer >> result.txt
task2
read -n 1 answer < /dev/tty
echo $answer >> result.txt
问题是,如果我意外地按两次键盘,第二个字符将保留在内存中并将其写为下一个答案。
我希望在file.txt中写入第一个字符后插入一个刷新内存的命令 感谢
答案 0 :(得分:2)
只需添加一个read
即可吞下该行,直到下一次返回。
task1
read -n 1 answer
echo $answer >> result.txt
read
task2
read -n 1 answer
echo $answer >> result.txt
read
答案 1 :(得分:2)
由于您没有使用 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.
答案 2 :(得分:0)
试试这个:
task 1
read first
answer=`cut -b1 <<<$first`
echo $answer >> result.txt
task 2
read second
answer=`cut -b1 <<<$second`
echo $answer >> result.txt
无法在shell中刷新输入缓冲区。
答案 3 :(得分:0)
这将满足您的要求:
{
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