Linux-shell读取键盘上下左右的问题?

需求定制 需求定制 主题:1050 回复:2283

Linux-shell读取键盘上下左右的问题?

偏爱自由 发布于 2017-03-24 字数 672 浏览 971 回复 2

方向键值查出来的,应该没错。不知哪里有错,请教。
代码如下

#!/bin/sh

uparrowkey='^[[A'
downarrowkey='^[[B'
leftarrowkey='^[[D'
rightarrowkey='^[[C'

#---------------------------------------------------
echo "Press a control key then hit return"
read KEY
echo $KEY
case $KEY in
$uparrowkey)
echo "UP Arrow"
;;
$downarrowkey)
echo "DOWN Arrow"
;;
$leftarrowkey)
echo "LEFT Arrow"
;;
$rightarrowkey)
echo "RIGHT Arrow"
;;
*)
echo "UNKNOW KEY $Key"
;;
esac

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

支持 Markdown 语法,需要帮助?

评论(2

偏爱自由 2017-06-12 2 楼

用cat -v看到这些方向键输入的字符,长度是3,只须判断最后一个字符,即A,B,C,D,即可:

!/bin/sh

echo "Press a control key then hit return"

while :
do
read -s -n 1 KEY

case ${KEY[0]} in
    "A")
        echo "UP Arrow"
        ;;
    "B")
        echo "DOWN Arrow"
        ;;
    "D")
        echo "LEFT Arrow"
        ;;
    "C")
        echo "RIGHT Arrow"
        ;;
esac

done

瑾兮 2017-05-22 1 楼

使用grep匹配:

  #!/bin/sh
uparrowkey='[A'
downarrowkey='[B'
leftarrowkey='[D'
rightarrowkey='[C'

echo "Press a control key then hit return"
read  KEY
count=`echo "$KEY" | grep -c "$downarrowkey"`
if [ "$count" -gt 0 ]
then
     echo "down"
     exit $?
fi
count=`echo "$KEY" | grep -c "$uparrowkey"`
if [ "$count" -gt 0 ]
then
   echo "up"
   exit $?
fi
count=`echo "$KEY" | grep -c "$leftarrowkey"`
if [ "$count" -gt 0 ]
then
   echo "left"
   exit $?
fi
count=`echo "$KEY" | grep -c "$rightarrowkey"`
if [ "$count" -gt 0 ]
then
   echo "right"
   exit $?
fi

echo "unknow"
exit