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

岁酱吖の 提交于 2019-11-30 09:20:37

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.

#!/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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!