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 
$
相关推荐
飞奔的瓜牛11 分钟前
Nginx + HAProxy 实现 TCP 代理:架构设计与实战配置
运维·tcp/ip·nginx
蝶依斓(湖南)全案整装19 分钟前
整装企业内容中的施工进度表述:节点、周期、反馈机制怎么写
运维
xixiaoyunya29 分钟前
FTP 文件备份的替代思路:用点对点自动化工具降低部署和维护成本
运维·备份
老一岁1 小时前
Redis事务_锁_持久化_主从哨兵
linux·数据库·redis
梓沂1 小时前
零成本替代 FTP:Ubuntu 24.04 搭建 Samba 共享,实现“一人可写,多人只读”
linux·运维·ubuntu
EmbeddedChen1 小时前
Linux 定时任务怎么设置?用 cron 自动执行脚本
linux·crontab·cron
IT小小猪1 小时前
子进程闪黑窗:pythonw 没有控制台,0x08000000 一个参数解决
运维·windows·python·自动化·进程管理
SHENGWEI胜为1 小时前
胜为CZDF-624六类24口免打配线架怎么安装?机房布线实操解析
服务器·网络·综合布线·rj45接口·胜为光通信·六类配线架
wuminyu2 小时前
OpenJDK学习笔记:Native事件队列与Java回调背压
java·linux·c语言·jvm·c++
图映 图片处理2 小时前
浏览器本地压缩图片安全吗:基于网络请求与文件传输的验证方法
服务器·网络·安全