Bash 读取退格按钮行为问题
在 bash 中使用 read 时,按退格键不会删除最后输入的字符,但会在输入缓冲区中追加一个退格键。有什么方法可以更改它,以便删除删除从输入中键入的最后一个键?如果是这样怎么办?
这是一个简短的示例程序,我正在使用它,如果它有任何帮助的话:
#!/bin/bash
colour(){ #$1=text to colourise $2=colour id
printf "%s%s%s" $(tput setaf $2) "$1" $(tput sgr0)
}
game_over() { #$1=message $2=score
printf "\n%s\n%s\n" "$(colour "Game Over!" 1)" "$1"
printf "Your score: %s\n" "$(colour $2 3)"
exit 0
}
score=0
clear
while true; do
word=$(shuf -n1 /usr/share/dict/words) #random word from dictionary
word=${word,,} #to lower case
len=${#word}
let "timeout=(3+$len)/2"
printf "%s (time %s): " "$(colour $word 2)" "$(colour $timeout 3)"
read -t $timeout -n $len input #read input here
if [ $? -ne 0 ]; then
game_over "You did not answer in time" $score
elif [ "$input" != "$word" ]; then
game_over "You did not type the word correctly" $score;
fi
printf "\n"
let "score+=$timeout"
done
When using read in bash, pressing backspace does not delete the last character entered, but appears to append a backspace to the input buffer. Is there any way I can change it so that delete removes the last key typed from the input? If so how?
Here's a short example prog I'm using it with if it's of any help:
#!/bin/bash
colour(){ #$1=text to colourise $2=colour id
printf "%s%s%s" $(tput setaf $2) "$1" $(tput sgr0)
}
game_over() { #$1=message $2=score
printf "\n%s\n%s\n" "$(colour "Game Over!" 1)" "$1"
printf "Your score: %s\n" "$(colour $2 3)"
exit 0
}
score=0
clear
while true; do
word=$(shuf -n1 /usr/share/dict/words) #random word from dictionary
word=${word,,} #to lower case
len=${#word}
let "timeout=(3+$len)/2"
printf "%s (time %s): " "$(colour $word 2)" "$(colour $timeout 3)"
read -t $timeout -n $len input #read input here
if [ $? -ne 0 ]; then
game_over "You did not answer in time" $score
elif [ "$input" != "$word" ]; then
game_over "You did not type the word correctly" $score;
fi
printf "\n"
let "score+=$timeout"
done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
选项
-n nchars
将终端转换为原始模式,因此最好的机会是依赖readline
(-e) [docs]:顺便说一句,好主意,尽管我会将单词的结尾留给用户(这是按 返回)。
The option
-n nchars
turns the terminal into raw mode, so your best chance is to rely onreadline
(-e) [docs]:BTW, nice idea, although I would leave the end of the word to the user (it's a knee-jerk reaction to press return).
我知道这篇文章很旧,但这对某人来说仍然有用。如果您需要对退格键上的单个按键进行特定响应,可以使用类似的方法(不带 -e):
I know the post is old, still this can be useful for someone. If you need specific response to a single keypress on backspace, something like this can do it (without -e):