Casing arrow keys in bash

前端 未结 8 836
遥遥无期
遥遥无期 2020-12-10 06:45

Is it possible to case arrow keys in a bash script to run a certain set of commands if the up/left arrow keys are pressed, and a certain set if the down/right arrow keys are

8条回答
  •  粉色の甜心
    2020-12-10 07:15

    None of the above answers have worked for me! I had to grab bits and pieces from many answers in this thread, as well as other searches via google. It took me about an hour to concoct this.

    I am running Ubuntu 20.04 LTS and this works for me (although, it may not be perfect, as I had to 'hack' at it):

    waitkey() {
      local end=""
      local key=""
    
      echo
      echo "   Press ESC ... "
    
      while [ "$end" == "" ]; do
        read -rsn1 key
        case "$key" in
          $'\x1b')
            local k=""
            # I'm not sure why I have to do this if statement,
            # but without it, there are errors.  took forever
            # to figure out why 'read' would dump me outta the script
            if [ "$IFS" ]; then
              read -rsn1 -t 0.1 holder && k="$holder"
            else
              IFS=read -rsn1 -t 0.1 holder && k="$holder"
            fi 
    
            if [ "$k" == "[" ]; then
              read -rsn1 -t 0.1 holder && kk="$holder"
    
              ##############################
              # you put your arrow code here
              #
              # eg:
              #  case "$kk" in
              #    "A") echo "up arrow!" ;; # do something ...
              #  esac
              ##############################
            elif [ "$k" == "O" ]; then
              read -rsn1 -t 0.1 holder && kk="$holder"
    
              # I am honestly not knowing what this is for
            elif [ "$k" == "" ]; then
              end=1
            fi
        esac
      done
    }
    

提交回复
热议问题