7

在 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
4

2 回答 2

11

该选项-n nchars将终端转换为原始模式,因此您最好的机会是依靠readline(-e) [docs]

$ read -n10 -e VAR

顺便说一句,好主意,尽管我会将单词的结尾留给用户(按return是下意识的反应)。

于 2010-11-16T16:32:56.500 回答
1

我知道帖子很旧,但这仍然对某人有用。如果您需要对退格键上的单个按键做出特定响应,可以这样做(不带 -e):

backspace=$(cat << eof
0000000 005177
0000002
eof
)
read -sn1 hit
[[ $(echo "$hit" | od) = "$backspace" ]] && echo -e "\nDo what you want\n"
于 2018-12-16T12:10:27.593 回答