shell_50.Linux获取用户输入_超时

超时

使用 read 命令时要当心。脚本可能会一直苦等着用户输入。如果不管是否有数据输入,脚

本都必须继续执行,你可以用-t 选项来指定一个计时器。-t 选项会指定 read 命令等待输入的

秒数。如果计时器超时,则 read 命令会返回非 0 退出状态码:

复制代码
$ cat asknametimed.sh 
#!/bin/bash 
# Using the read command with a timer 
# 
if read -t 5 -p "Enter your name: " name 
then 
    echo "Hello $name, welcome to my script." 
else 
    echo 
    echo "Sorry, no longer waiting for name." 
fi 
exit 
$ 
$ ./asknametimed.sh 
Enter your name: Christine 
Hello Christine, welcome to my script. 
$ 
$ ./asknametimed.sh 
Enter your name: 
Sorry, no longer waiting for name. 
$

可以不对输入过程计时,而是让 read 命令统计输入的字符数。当字符数达到预设值时,

就自动退出,将已输入的数据赋给变量:

复制代码
$ cat continueornot.sh 
#!/bin/bash 
# Using the read command for one character 
# 
read -n 1 -p "Do you want to continue [Y/N]? " answer 
# 
case $answer in 
    Y | y) echo 
        echo "Okay. Continue on...";; 
    N | n) echo 
    echo "Okay. Goodbye" 
    exit;; 
esac 
echo "This is the end of the script." 
exit 
$ 
$ ./continueornot.sh

Do you want to continue [Y/N]? Y
Okay. Continue on... 
This is the end of the script. 
$ 
$ ./continueornot.sh 
Do you want to continue [Y/N]? n
Okay. Goodbye 
$
相关推荐
学***542313 分钟前
换新电脑如何迁移原有数据?4 种高效数据迁移方法详解
服务器·电脑·负载均衡
vortex56 小时前
Debian 包管理全指南:从底层 dpkg 到高层 apt 及其日志追踪
linux·运维·debian
偶尔上线经常挺尸6 小时前
《每日一命令08:scp——安全的远程复制》
linux·安全·scp·文件传输·运维基础·远程复制
计算机安禾6 小时前
【Linux从入门到精通】第17篇:日志系统——系统运行的黑匣子
linux·运维·服务器
l1t6 小时前
DeepSeek辅助解决windows 11 wsl2中Linux版Dbeaver显示中文
linux·运维·windows
pengyi8710158 小时前
独享IP+动态IP结合核心逻辑,破解稳定与灵活的矛盾
linux·运维·网络
阿祖zu8 小时前
本地到生产,解决 AI 全栈最后一公里——构建&部署&运维
运维·架构·aigc
拍客圈12 小时前
内容页底部 采集的同时 隐瞒封面图
服务器·php
MAVER1CK12 小时前
Install VNC in Docker container
运维·docker·容器
SECS/GEM13 小时前
SECS/GEM如何实现越南现场自定义消息
java·服务器·数据库