Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash read backspace button behavior problem

Tags:

bash

backspace

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
like image 334
Ultimate Gobblement Avatar asked Nov 16 '10 16:11

Ultimate Gobblement


2 Answers

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

like image 68
tokland Avatar answered Sep 23 '22 00:09

tokland


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"
like image 25
Guariba Som Avatar answered Sep 20 '22 00:09

Guariba Som