如何在Bash脚本中实现用户无响应5秒超时提示功能?
Bash脚本实现带超时的用户响应检测
你的现有脚本功能是询问姓名并让用户确认,但需要在用户5秒未响应时输出提示。Bash的read命令本身支持-t参数设置超时时间,不需要额外的并行sleep操作,以下是修改后的实现方案:
原始脚本
#! /bin/bash num=0 while [ $num -lt 1 ] do echo "What is your name?" read name echo "Your name is $name? Respond with Y or N" read response if [ $response == "Y" ]; then echo "What an interesting name $name" num=1 break elif [ $response == "N" ]; then echo "Why would you lie $name? Wait that's not even you" continue else echo "Why don't you respond $name, or are you lying?" continue fi done
修改后的脚本(添加超时检测)
#!/bin/bash num=0 while [ $num -lt 1 ] do echo "What is your name?" read name echo "Your name is $name? Respond with Y or N" # 使用read -t设置5秒超时,超时后read返回非0状态码 if read -t 5 response; then # 用户在超时前输入了内容 if [ "$response" == "Y" ]; then echo "What an interesting name $name" num=1 break elif [ "$response" == "N" ]; then echo "Why would you lie $name? Wait that's not even you" continue else echo "Why don't you respond $name, or are you lying?" continue fi else # 超时未响应的处理逻辑 echo "Hey, you didn't respond in time! Let's try again." continue fi done
关键说明
read -t 5 response:-t参数指定超时时间为5秒,若用户在5秒内输入并回车,read执行成功(返回0),否则返回非0状态码。- 通过
if read -t 5 response; then ... else ... fi判断用户是否超时,分别处理正常输入和超时情况。 - 若需给“输入姓名”步骤也添加超时,只需将
read name改为read -t 5 name,并补充对应的超时处理逻辑即可。
内容的提问来源于stack exchange,提问作者AlexE
相关产品推荐
相关产品推荐

