Bash 读取退格按钮行为问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4196161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:55:34  来源:igfitidea点击:

Bash read backspace button behavior problem

bashbackspace

提问by Ultimate Gobblement

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?

在 bash 中使用 read 时,按退格键不会删除输入的最后一个字符,而是会在输入缓冲区中附加一个退格符。有什么方法可以更改它,以便删除删除从输入中键入的最后一个键?如果是这样怎么办?

Here's a short example prog I'm using it with if it's of any help:

这是一个简短的示例程序,如果有帮助,我正在使用它:

#!/bin/bash

colour(){ #=text to colourise =colour id
        printf "%s%s%s" $(tput setaf ) "" $(tput sgr0)
}
game_over() { #=message =score      
        printf "\n%s\n%s\n" "$(colour "Game Over!" 1)" ""
        printf "Your score: %s\n" "$(colour  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

回答by tokland

The option -n ncharsturns the terminal into raw mode, so your best chance is to rely on readline(-e)[docs]:

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

$ read -n10 -e VAR

BTW, nice idea, although I would leave the end of the word to the user (it's a knee-jerk reaction to press return).

顺便说一句,好主意,虽然我会把词的结尾留给用户(按回车是下意识的反应)。

回答by Guariba Som

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):

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

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