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 
$
相关推荐
Ivanqhz4 分钟前
矩阵引擎的数据流模式与 BM1684X 架构
java·服务器·网络·深度学习·神经网络
高亦真1 小时前
今天是学习嵌入式的第39天
linux·学习·算法
AR-26710-1 小时前
Linux Day8——FHS文件系统层次
linux
小葱运维1 小时前
日志规范(K8s 结构化日志)
运维·开源·云计算
其实防守也摸鱼2 小时前
DeepSeek Harness 开源贡献手记:从入门到合入主线
服务器·数据库·windows·https·ssl
qq_297670872 小时前
Ubuntu 打开系统应用老弹密码?三步彻底关闭免密
linux
杨云龙UP2 小时前
DB2 HADR 主备切换实战:SQL1639N 认证问题、备库只读与双向 Takeover
linux·运维·数据库·db2·主备切换·角色互换
Wang's Blog2 小时前
Java 接入Redis: 密码认证与远程连接配置
java·服务器·redis
半仙白桑2 小时前
内核篇第一讲:linux创建进程
linux·fork·创建进程