2010-04-10 219 views
12

我需要比较我与输入回车/返回关键...的Bash shell脚本 - 返回键/回车键

read -n1 key 
if [ $key == "\n" ] 
    echo "@@@" 
fi 

但是这是行不通的。什么是不对的代码

+1

您在“if”和“echo”之间的线上缺少“then”。不是唯一的问题,但一个 – Phil 2010-04-10 04:56:12

回答

28

发布代码的几个问题。行内注释详细解决什么:

#!/bin/bash 
# ^^ Bash, not sh, must be used for read options 

read -s -n 1 key # -s: do not echo input character. -n 1: read only 1 character (separate with space) 

# double brackets to test, single equals sign, empty string for just 'enter' in this case... 
# if [[ ... ]] is followed by semicolon and 'then' keyword 
if [[ $key = "" ]]; then 
    echo 'You pressed enter!' 
else 
    echo "You pressed '$key'" 
fi 
4

read从标准输入读取一行,直到但不包括行尾的新行。 -n指定最大字符数,如果达到该字符数,则迫使read提前返回。它仍然会提前结束,但当返回键被按下时。在这种情况下,它返回一个空字符串 - 一切都达到但不包括返回键。

您需要与空字符串进行比较以判断用户是否立即按下返回

read -n1 KEY 
if [[ "$KEY" == "" ]] 
then 
    echo "@@@"; 
fi 
1

此外,它是不错的主意定义进行比较之前空$ IFS(内部字段分隔符),否则你可以有“”,“\ n”等于结束。

因此,代码应该是这样的:

# for distinguishing " ", "\t" from "\n" 
IFS= 

read -n 1 key 
if [ "$key" = "" ]; then 
    echo "This was really Enter, not space, tab or something else" 
fi 
+0

#这对我来说不起作用,如果使用循环打印coutdown IFS = echo -e“按[ENTER]键盘配置。” ((i = 10; i> 0; i--))的 ; do printf“\ r以$ i秒开始...” 已读-n 1 -t 1键 if [“$ key”= $'\ e'];然后 回声“这是ESC” 破 的elif [“$键” ==“”;然后 回声-e“\ n空格键被按下” 破 网络 做 – 2016-04-25 13:34:47

+0

也许事情是,内联语法你应该使用IFS =;回声...(用分号) – tsds 2016-04-25 14:39:35

0

我添加以下代码仅供参考,如果有人想使用含倒计时循环等解决方案。

IFS='' 
echo -e "Press [ENTER] to start Configuration..." 
for ((i=10; i>0; i--)); do 

printf "\rStarting in $i seconds..." 
read -s -N 1 -t 1 key 

if [ "$key" = $'\e' ]; then 
     echo -e "\n [ESC] Pressed" 
     break 
elif [ "$key" == $'\x0a' ] ;then 
     echo -e "\n [Enter] Pressed" 
     break 
fi 

done