繁体   English   中英

如何在 Bash 中检测 Enter 键或无输入?

[英]How to detect Enter key or no input in Bash?

我想写一个脚本在 X 秒后运行程序,如果用户按 Enter 可以停止它

但它无法检测用户是否按下了 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

如果发生超时, read失败(即返回非零返回码)。 所以就这么简单:

if read -t 1
then
  echo Enter pressed
else
  echo Timeout happened
fi

所以在你的情况下,像这样的事情,也许?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM