Search code examples
bashif-statementinputcasectrl

Recognizing Ctrl+KEY in case in bash


I've searched forever for an answer and cannot find one, so now i must ask.

Im working on a script in that creates a textstring as a T9 Numpad (without the dictionary) by cycling through each keys letters. All of it is working except handling backspace (a real backspace on the numpad). I use "Read -n 1" for the inputs and as far as i have learned backspace maps to "^?" and as far as i know the "^" corresponds to ctrl being pressed while typing "?". I cannot get a case to handle this input, and i dont know what to do. The code works if i substitute backspace for any single key i.e. "-". So i only need to know how i would be able recognize the backspace in read -n and case


Solution

  • You can use $'...' notation to match a control character in bash. ^? is a C-style notation to represent ASCII 127 (DEL). There are several options:

    * $'\177' - octal
    * $'\x7f' - hexadecimal
    

    any of which can be used as a literal pattern to match in the case statement.

    read -n 1 char
    case $char in
        $'\177') echo "Backspace" ;;
    esac