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 
$
相关推荐
叼烟扛炮1 小时前
[LangChain] 学习笔记(15):为什么你的重试没用——429、抖动、fallback 与熔断
java·服务器·前端
hi_ro_a2 小时前
Ext系列⽂件系统详解
linux·服务器·操作系统
Z21-X3 小时前
云原生运维学习笔记:Kubernetes Volume 与 Secret 实验
运维·笔记·学习·云原生·kubernetes
你住过的屋檐4 小时前
【SeaweedFS】Linux上搭建SeaweedFS文件存储服务完整教程
linux·运维·服务器
Decay__5 小时前
PostgreSQL 体系架构全解 —— 进程模型、共享内存、MVCC 与 WAL 预写日志深入
运维·数据库·sql·mysql·架构
少司府5 小时前
嵌入式外设篇(三)GPIO·三:MCU系统结构、总线与统一编制
linux·python·stm32·单片机·嵌入式硬件·mcu·嵌入式软件
分布式存储与RustFS5 小时前
桶里的文件想当目录使:用 ZeroFS 把 RustFS 挂成一棵 POSIX 树
运维·云原生·开源·对象存储·分布式存储·s3·性能基准
老余说AI6 小时前
跨境电商、课程出海:六款多语言视频翻译工具选型指南
大数据·运维·人工智能
不积跬步无以至千里mmbb266 小时前
Rust三大核心:Trait Crate Mod详解
linux·rust
分布式存储与RustFS7 小时前
向量表别堆本地盘:用 LanceDB 把数据集建在 RustFS 上
运维·云原生·开源·对象存储·分布式存储·s3·性能基准