[英]How to detect Enter key or no input in Bash?
I want to write a script to run a program after X seconds, it can be stopped if user press Enter我想写一个脚本在 X 秒后运行程序,如果用户按 Enter 可以停止它
But it cannot detect whether user pressed Enter key or no input但它无法检测用户是否按下了 Enter 键或没有输入
#!/bin/bash
seconds=$((5))
holder='000'
while [ $seconds -gt 0 ]; do
if [[ $holder = "" ]]; then
echo "Stop"
exit
else
echo "Start in $seconds seconds, Press Enter to stop"
fi
IFS= read -r -t 1 -n 1 -s holder && var="$holder"
: $((seconds--))
done
echo Start
If timeout happens, read
fails (ie returns a non-zero return code).如果发生超时,
read
失败(即返回非零返回码)。 So it is as simple as this:所以就这么简单:
if read -t 1
then
echo Enter pressed
else
echo Timeout happened
fi
So in your case, something like this, maybe?所以在你的情况下,像这样的事情,也许?
seconds=5
while [[ "$seconds" -gt 0 ]]; do
echo "Start in $seconds seconds, Press Enter to stop"
if read -t 1 -s
then
echo Stop
exit
else
((seconds--))
fi
done
echo Start
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.