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 小时前
磁盘级文件系统核心原理解析
linux·文件
醇氧1 小时前
【Linux】 安装 Azul Zulu JDK
java·linux·运维
一直跑2 小时前
查看显卡驱动版本,查看哪个用户使用显卡(GPU)进程
linux·服务器
滴水之功2 小时前
Windows远程桌面(非图形化界面)连接Ubuntu22.04
linux
借你耳朵说爱你3 小时前
在Linux上挂载磁盘
linux
小成202303202653 小时前
Linux高级
linux·开发语言
ICT系统集成阿祥4 小时前
Linux运维最万能的三条指令
linux·运维·服务器
CAU界编程小白4 小时前
Linux系统编程系列之模拟文件操作
linux·算法
chenyuhao20244 小时前
Linux网络编程:数据链路层
linux·运维·网络
QT 小鲜肉4 小时前
【Linux命令大全】002.文件传输之uupick命令(实操篇)
linux·运维·服务器·chrome·笔记