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 
$
相关推荐
l1t7 分钟前
DeepSeek总结的在 NVIDIA Vera 上对 DuckDB v2.0-dev 进行基准测试
服务器·数据库·sql
。9 分钟前
【无标题】
linux·服务器·负载均衡·lvs
励志师code10 分钟前
Kubernetes 集群节点生命周期管理实战:从扩容、调度管控到证书续期
运维·docker·容器·kubernetes·gpu算力·kubelet
weixin_4166679612 分钟前
linux ping命令详解
linux·运维·php
润滑卫士12 分钟前
NAS 1638 油液清洁度等级:检测方法、影响因素与控制策略
运维
硅基手札22 分钟前
【Linux 内核专栏 17】进程间通信 IPC(上)— 管道·信号·System V IPC·mmap·文件锁
linux·运维·服务器·stm32·单片机·mcu
小能喵22 分钟前
kismet -h 帮助信息 中文版
linux·服务器·网络
seuzhouchenglong24 分钟前
服务器通过本地电脑连接本地开发板
运维·服务器
AR-26710-28 分钟前
Linux Day21——systemctl操作
linux·运维
臻选云栗子38 分钟前
PCDN晚高峰掉量原因分析及优化建议
服务器·网络·安全·网络安全·阿里云·云计算·信息与通信