Home > Back-end >  How to detect backspace and remove last character in shell script?
How to detect backspace and remove last character in shell script?

Time:10-07

I want to remove last character once user presses delete key on mac.

INPUT=''


while true
do
 IFS= read -rsn1 char
 INPUT=$INPUT$char
 echo $INPUT
done

CodePudding user response:

Depending on your keyboard setup, the delete key will return either character code of 8 (backspace), or 127 (delete). You can test for those characters

while true
do
    IFS= read -rsn1 char
    if [ "$char" = $'\x7f' -o "$char" = $'\x08' ]
    then
         INPUT=${INPUT:0:-1}
    else
         INPUT=$INPUT$char
    fi
    echo $INPUT
done

As a side note, consider using the built-in readline, which will provide much better line editing

  • Related