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 
$
相关推荐
我是伪码农12 分钟前
注册表单提交加验证码功能
运维·服务器
范纹杉想快点毕业20 分钟前
嵌入式C语言实战开发详解
linux·运维·算法
天骄t24 分钟前
数据库入门:SQLite实战指南
linux
hanyi_qwe32 分钟前
Docker 镜像的创建 【docker (四)】
运维·docker·容器
张某人的胡思乱想38 分钟前
周末随笔-整理ubuntu环境
linux·运维·ubuntu
翔云 OCR API1 小时前
智能发票查验接口在财务自动化中的技术实现与应用价值
linux·运维·自动化
硬核子牙1 小时前
送别2025,喜迎2026
linux
盛世宏博北京1 小时前
从服务器机房到 IDC 集群:网口温湿度变送器的全场景适配监控
运维·服务器
RPA机器人就选八爪鱼1 小时前
RPA在银行IT运维领域的应用场景与价值分析
大数据·运维·数据库·人工智能·机器人·rpa
大聪明-PLUS1 小时前
FUSE:如何编写自己的文件系统
linux·嵌入式·arm·smarc