7

read in bashを使用する場合、バックスペースを押しても最後に入力した文字は削除されませんが、入力バッファーにバックスペースが追加されているように見えます。削除によって入力から最後に入力されたキーが削除されるように変更する方法はありますか?もしそうなら、どのように?

これが助けになるなら私がそれを使っている短い例のプログラムです:

#!/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

このオプションは端末をrawモードに変えるので、 (-e)[docs]-n ncharsに頼るのが最善のチャンスです。readline

$ read -n10 -e VAR

ところで、いい考えですが、単語の終わりはユーザーに任せます( returnキーを押すのはひざまずく反応です)。

于 2010-11-16T16:32:56.500 に答える
1

投稿が古いことは知っていますが、それでもこれは誰かに役立つ可能性があります。バックスペースでの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 に答える