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 
$
相关推荐
木叶子---5 分钟前
Docker
运维·docker·容器
wdfk_prog6 分钟前
[Linux]学习笔记系列 -- bits
linux·笔记·学习
Xの哲學7 分钟前
Linux epoll 深度剖析: 从设计哲学到底层实现
linux·服务器·网络·算法·边缘计算
iYun在学C7 分钟前
驱动程序(注册字符设备)
linux·嵌入式硬件
延延oO21 分钟前
zyzyzyzyzy
linux
小白不想白a25 分钟前
linux排障:服务端口被打满
linux·服务器·网络
CryptoPP28 分钟前
对接API获取马来西亚历史数据
linux·运维·服务器·金融·区块链
Cyber4K42 分钟前
【Kubernetes专项】K8s集群1.31版本安装手册
linux·docker·云原生·容器·kubernetes
凯子坚持 c43 分钟前
基于Docker的SD-WAN组网方案:利用节点小宝实现服务器远程开发
服务器·docker·容器