bash scripting - read single keystroke including special keys enter and space

后端 未结 3 1953
轻奢々
轻奢々 2020-12-31 18:54

Not sure if I should put this on stackoverflow or unix.stackexchange but I found some similar questions here, so here it goes.

I\'m trying to create a script to be c

相关标签:
3条回答
  • 2020-12-31 19:36
    #!/bin/bash
    SELECT=""
    # prevent parsing of the input line
    IFS=''
    while [[ "$SELECT" != $'\x0a' && "$SELECT" != $'\x20' ]]; do
      echo "Select session type:"
      echo "Press <Enter> to do foo"
      echo "Press <Space> to do bar"
      read -s -N 1 SELECT
      echo "Debug/$SELECT/${#SELECT}"
      [[ "$SELECT" == $'\x0a' ]] && echo "enter" # do foo
      [[ "$SELECT" == $'\x20' ]] && echo "space" # do bar
    done
    
    0 讨论(0)
  • 2020-12-31 19:47

    Try setting the read delimiter to an empty string then check the builtin $REPLY variable:

    read -d'' -s -n1
    

    For some reason I couldn't get it to work specifying a variable.

    0 讨论(0)
  • 2020-12-31 19:52

    There are a couple of things about read that are relevant here:

    • It reads a single line
    • The line is split into fields as with word splitting

    Since you're reading one character, it implies that entering Enter would result into an empty variable.

    Moreover, by default rules for word splitting, entering Space would also result into an empty variable. The good news is that you could handle this part by setting IFS.

    Change your read statement to:

    IFS= read -s -n 1 SELECT
    

    and expect a null string instead of $'\x0a' when entering Enter.

    0 讨论(0)
提交回复
热议问题