Bash Shell 脚本 - 返回键/回车键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2612274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:09:36  来源:igfitidea点击:

Bash Shell Scripting - return key/Enter key

bashshell

提问by veda

I need to compare my input with Enter/Returnkey...

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

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

But this is not working.. What is wrong with this code

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

回答by Mark Rushakoff

Several issues with the posted code. Inline comments detail what to fix:

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

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

回答by tsds

Also it is good idea to define empty $IFS (internal field separator) before making comparisons, because otherwise you can end up with " " and "\n" being equal.

在进行比较之前定义空的 $IFS(内部字段分隔符)也是一个好主意,否则你最终可能会得到 " " 和 "\n" 相等。

So the code should look like this:

所以代码应该是这样的:

# 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

回答by Asaf Magen

I'm adding below code just for reference if someone will want to use such solution containing countdown loop.

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

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

回答by meagar

readreads a line from standard input, up to but not including the new line at the end of the line. -nspecifies the maximum number of characters, forcing readto return early if you reach that number of characters. It will still end earlier however, when the Returnkey is pressed. In this case, its returning an empty string - everything up to but not including the Returnkey.

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

You need to compare against the empty string to tell if the user immediately pressed Return.

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

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