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 
$
相关推荐
宵时待雨4 分钟前
linux笔记归纳25:多路转接epoll
linux·服务器·网络·c++
geats人山人海26 分钟前
linux 1.目录结构
linux·运维·服务器
wuminyu30 分钟前
JEP491中synchronized关键字引发的平台线程钉住解决方法简介
java·linux·c语言·jvm·c++
应用市场1 小时前
嵌入式Linux从裸板到产品(一):全景地图与交叉编译环境,从四个上板翻车现场说
linux·运维·服务器
CIMPro孪大师1 小时前
CIMPro×DPE | 不止是爆炸动画,AI原生数字样机如何让设备培训与运维更高效
运维·ai-native
皓月盈江1 小时前
Linux系统PC与Linux系统服务器通过scp上传与下载文件
linux·运维·服务器·scp·文件上传·文件下载
对讲机数码科普1 小时前
危化厂区防爆专网通信建设实践:从合规框架到验收清单
运维·网络·架构
Ruiery1 小时前
Linux 6.6内核 CPU 启动深度解析(二):AP 拉起 — BSP 如何用 INIT-SIPI 唤醒其余 CPU
linux·运维·服务器
Lsetea1 小时前
OpenSSL verify报error 62:证书主机名不匹配与-verify_hostname排查
运维·https·ssl证书·openssl·san
xcLeigh1 小时前
【KingbaseES数据库教程】国产化信创背景下的数据库选型与初识
linux·数据库·windows·kes·数据选型