嗨,我正在尝试实施一个在5秒倒计时后发生的事件,除非按下一个键.我一直在使用这段代码,但是如果按下回车键或空格键就会失败.在输入或空间被检测为""的意义上它失败了.
echo "Phoning home..."
key=""
read -r -s -n 1 -t 5 -p "Press any key to abort in the next 5 seconds." key
echo
if [ "$key" = "" ] # No Keypress detected, phone home.
then python /home/myuser/bin/phonehome.py
else echo "Aborting."
fi
Run Code Online (Sandbox Code Playgroud)
阅读完这篇文章后, Bash:检查输入是否被按下
我放弃了,贴在这里.我觉得必须有比我试图实施的更好的方法.
链接问题中接受的答案涵盖了问题的“检测”部分。您查看退出代码。enter
read
至于处理空间有两个答案。
空格的问题是,在正常情况下,read
在将输入分配给给定变量时,会修剪输入中的前导和尾随空格(并对输入进行分词)。
有两种方法可以避免这种情况。
您可以避免使用自定义命名变量并使用$REPLY
它。当分配给$REPLY
不执行空白修剪或分词时。(虽然现在我正在寻找这个,但实际上我在 POSIX 规范中找不到它,所以这可能是某种非标准和/或不可移植的扩展。)
为命令显式设置IFS
为空字符串read
,以便它不执行空格修剪或分词。
$ IFS= read -r -s -n 1 -t 5 -p "Press any key to abort in the next 5 seconds." key; echo $?
# Press <space>
0
$ declare -p key
declare -- k=" "
$ unset -v k
$ IFS= read -r -s -n 1 -t 5 -p "Press any key to abort in the next 5 seconds." key; echo $?
# Wait
1
$ declare -p key
-bash: declare: k: not found
Run Code Online (Sandbox Code Playgroud)