代码之家  ›  专栏  ›  技术社区  ›  Ultimate Gobblement

bash read backspace按钮行为问题

  •  7
  • Ultimate Gobblement  · 技术社区  · 15 年前

    在bash中使用read时,按backspace不会删除输入的最后一个字符,但会向输入缓冲区追加一个backspace。是否有任何方法可以更改它,以便删除从输入中删除最后键入的密钥?如果是这样怎么办?

    下面是一个简短的示例程序,如果有任何帮助,我将使用它:

    #!/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 回复  |  直到 7 年前
        1
  •  11
  •   tokland    13 年前

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

    $ read -n10 -e VAR
    

    顺便说一句,好主意,尽管我会把词尾留给用户(这是对媒体的膝跳反应) 返回 )

        2
  •  0
  •   Guariba Som    7 年前

    我知道这篇文章很旧,但对某些人来说还是有用的。如果您需要对退格键上的单个按键做出特定的响应,可以这样做(不使用-e):

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