Bash读取退格键行为问题

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
2个回答

11

选项-n nchars将终端设为原始模式,因此你最好依靠readline (-e)[文档]

$ read -n10 -e VAR

顺便说一下,这是个好主意,尽管我会让用户自己决定单词的结尾(按下“回车”键是一个下意识的反应)。


1
在manpage上的所有开关中,-e是我没有尝试过的唯一一个 o_O。无论如何,这让它按照我想要的方式工作了,但有一个小问题:如果我在输入一个字符时按下删除键,整个前面的行都会被删除。不过似乎将额外的-p“ ”添加到命令中可以解决这个问题。干杯! - Ultimate Gobblement
just use -e flag - danday74

1

我知道这篇文章已经过时了,但对某些人仍然有用。如果你需要在按下退格键时得到特定的响应,可以使用类似以下代码(不需要 -e 参数):

backspace=$(cat << eof
0000000 005177
0000002
eof
)
read -sn1 hit
[[ $(echo "$hit" | od) = "$backspace" ]] && echo -e "\nDo what you want\n"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接