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 
$
相关推荐
Nautiluss10 分钟前
一起调试XVF3800麦克风阵列(十四)
linux·人工智能·音频·语音识别·dsp开发
运维有小邓@11 分钟前
Log360 的可扩展架构实践:常见场景
运维·网络·架构
热心市民R先生27 分钟前
IGH EtherCAT 主站核心文件体系全解析:构成、区别与运维实践
运维·服务器·网络
耶耶耶耶耶~1 小时前
arch linux 安装
linux·运维·服务器
kft13141 小时前
Rocky Linux 9.4 磁盘扩展至根目录(/)教程
运维
iYun在学C1 小时前
驱动程序开发(字符设备驱动框架实验)
linux·c语言·嵌入式硬件
gsls2008081 小时前
阿里云两个数据盘合并挂载
运维·挂载
ashcn20011 小时前
linux 制作一个自解压文件
linux·运维·服务器
hhzz1 小时前
EasyPoi的核心映射工具:@Excel注解详解
java·服务器·excel·springboot·easypoi
天码-行空1 小时前
Linux 系统 MySQL 8.0 详细安装教程
linux·运维·mysql