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 
$
相关推荐
珠海西格电力2 小时前
零碳园区工业厂房光伏一体化(BIPV)基础规划
大数据·运维·人工智能·智慧城市·能源
HerayChen2 小时前
HbuilderX 内存溢出报错
java·大数据·linux
呱呱巨基3 小时前
Linux 进程概念
linux·c++·笔记·学习
土星云SaturnCloud3 小时前
不止是替代:从机械风扇的可靠性困局,看服务器散热技术新范式
服务器·网络·人工智能·ai
liulilittle3 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
Xの哲學3 小时前
Linux Miscdevice深度剖析:从原理到实战的完整指南
linux·服务器·算法·架构·边缘计算
你们补药再卷啦3 小时前
ai(二)ubuntu22.04配置环境
linux·ubuntu
yong15858553433 小时前
2. Linux C++ muduo 库学习——原子变量操作头文件
linux·c++·学习
泽02023 小时前
Linux信号专题
linux·运维·服务器
chuxinweihui3 小时前
数据链路层
运维·服务器·网络