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 
$
相关推荐
小赵还有头发19 分钟前
安装 RealSense SDK (驱动层)
linux
Root_Hacker1 小时前
include文件包含个人笔记及c底层调试
android·linux·服务器·c语言·笔记·安全·php
REDcker2 小时前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
微学AI2 小时前
内网穿透的应用-告别局域网束缚!MonkeyCode+cpolar 解锁 AI 编程新体验
linux·服务器·网络
sunnyday04262 小时前
基于Netty构建WebSocket服务器实战指南
服务器·spring boot·websocket·网络协议
信创天地2 小时前
国产堡垒机部署实战:以奇安信、天融信为例构建运维安全三重防线
运维·安全
呉師傅3 小时前
东芝3525AC彩色复印机CC219测试页打印方法【实际操作】
运维·网络·windows·计算机外设·电脑
凯子坚持 c4 小时前
Protocol Buffers C++ 进阶数据类型与应用逻辑深度解析
java·服务器·c++
宴之敖者、4 小时前
Linux——权限
linux·运维·服务器
刘叨叨趣味运维5 小时前
Linux性能排查实战:从“系统慢”到精准定位
linux