23

我需要将我的输入与Enter/Return键进行比较...

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

但这不起作用..这段代码有什么问题

4

5 回答 5

39

发布的代码有几个问题。内联注释详细说明了要修复的内容:

#!/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
于 2010-04-10T04:56:26.280 回答
7

此外,在进行比较之前定义空的 $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
于 2016-02-17T21:50:09.907 回答
6

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

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
于 2016-04-26T08:54:33.607 回答
4

read从标准输入读取一行,直到但不包括行尾的新行。 -n指定最大字符数,read如果达到该字符数,则强制提前返回。Return但是,当按下该键时,它仍会提前结束。在这种情况下,它返回一个空字符串 - 直到但不包括Return密钥的所有内容。

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

read -n1 KEY
if [[ "$KEY" == "" ]]
then
  echo "@@@";
fi
于 2010-04-10T04:50:27.033 回答
1

这些条件都不适合我,所以我想出了这个:

${key} = $'\0A'

在 CentOS 上使用 Bash 4.2.46 进行测试。

于 2020-10-06T16:28:01.587 回答