簡體   English   中英

如何清除bash中的輸入

[英]how to clear input in bash

我正在制作一個腳本,它在任務后讀取答案,然后將其寫入文本文件。 我希望這個答案只是一個字符:

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

問題是,如果我不小心按了兩次鍵盤,第二個字符會保留在內存中並將其寫為下一個答案。

我想插入一個命令,在 file.txt 中寫入第一個字符后刷新內存,謝謝

只需添加一個read ,該read將吞下該行直到下一個回車。

task1
read -n 1 answer
echo $answer >> result.txt
read
task2
read -n 1 answer
echo $answer >> result.txt
read

由於您沒有使用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.

試試這個:

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 中刷新輸入緩沖區。

這將執行您想要的操作:

{
  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM