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 
$
相关推荐
清风拂山岗 明月照大江几秒前
MySQL运维
运维·数据库·mysql
米高梅狮子4 分钟前
02. 配置DNS服务器
运维·服务器·centos
宴之敖者、18 分钟前
Linux——指令
linux·运维·服务器
Xの哲學1 小时前
Linux设备驱动模型深度解剖: 从设计哲学到实战演练
linux·服务器·网络·算法·边缘计算
半夏知半秋2 小时前
kcp学习-通用的kcp lua绑定
服务器·开发语言·笔记·后端·学习
Ydwlcloud2 小时前
AWS 2026折扣活动深度解析:寻找最大优惠的智慧路径
大数据·服务器·人工智能·云计算·aws
企业对冲系统官2 小时前
基差风险管理系统集成说明与接口规范
大数据·运维·python·算法·区块链·github
松涛和鸣2 小时前
DAY55 Getting Started with ARM and IMX6ULL
linux·服务器·网络·arm开发·数据库·html
HIT_Weston2 小时前
101、【Ubuntu】【Hugo】搭建私人博客:元信息&翻译(二)
linux·运维·ubuntu
无线图像传输研究探索2 小时前
如何提升机器狗 “超视距” 作战能力?
服务器·网络·5g·机器人·无线图传·机器狗