我需要将我的输入与Enter/ Returnkey 进行比较......
read -n1 key
if [ $key == "\n" ]
echo "@@@"
fi
Run Code Online (Sandbox Code Playgroud)
但这不起作用..这段代码有什么问题
Mar*_*off 34
发布代码的几个问题.内联注释详细说明要修复的内容:
#!/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
Run Code Online (Sandbox Code Playgroud)
在进行比较之前定义空的 $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
Run Code Online (Sandbox Code Playgroud)
如果有人想要使用包含倒计时循环的此类解决方案,我将添加以下代码仅供参考。
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
Run Code Online (Sandbox Code Playgroud)