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 
$
相关推荐
IMPYLH5 小时前
Linux 的 pinky 命令
linux·运维·服务器·bash
HelloWorld_SDK5 小时前
Docker安装OpenClaw
运维·docker·容器·openclaw
REDcker6 小时前
Linux iptables 与 Netfilter:原理、路径与运维要点
linux·运维·服务器
KKKlucifer7 小时前
零信任融合实践:国内堡垒机如何落地动态权限与实时阻断
运维
嵌入式×边缘AI:打怪升级日志7 小时前
Linux 驱动开发入门:从最简单的 hello 驱动到硬件交互
linux·驱动开发·交互
Bert.Cai8 小时前
Linux useradd命令详解
linux·运维
无忧.芙桃9 小时前
进程控制(上)
linux·运维·服务器
十年编程老舅9 小时前
深入 Linux 中断:原理详解 + 实战落地
linux·网络·linux内核·c/c++·中断
Bert.Cai9 小时前
Linux rm命令详解
linux·运维
航Hang*9 小时前
Windows Server 配置与管理——第8章:配置Web服务器
运维·服务器·windows·学习·vmware