Bash read backspace button behavior problem
Asked Answered
P

2

7

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
Papilloma answered 16/11, 2010 at 16:4 Comment(0)
F
11

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

Flee answered 16/11, 2010 at 16:32 Comment(2)
Out of all the switches on the manpage -e is the only one I did not try o_O. Anyway, that got it working how I want, with one quirk: if I press delete when one character is entered the whole preceding line is deleted. It seems adding an additional -p " " to the command seemed to fix it though. Cheers.Papilloma
just use -e flagCaduceus
D
1

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"
Decoction answered 16/12, 2018 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.