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?
Here's a short example prog I'm using it with if it's of any help:
#!/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
The option -n nchars
turns the terminal into raw mode, so your best chance is to rely on 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).
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):
backspace=$(cat << eof
0000000 005177
0000002
eof
)
read -sn1 hit
[[ $(echo "$hit" | od) = "$backspace" ]] && echo -e "\nDo what you want\n"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With