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 
$
相关推荐
小猿姐7 小时前
Clickhouse Kubernetes Operator 实测:哪种方案更适合生产?
运维·数据库·kubernetes
彩色的黑'''7 小时前
[root@localhost ~]#,Linux系统的命令提示符为啥现在变成-bash-4.2#了,哪里设置的
linux·运维·bash
树下水月7 小时前
文件分片上传接口(Easyswoole)被nginx拦截,并返回状态码400和408的抓包排查过程
运维·nginx
源远流长jerry8 小时前
Linux 网络发送机制深度解析:从应用到网线
linux·服务器·网络·网络协议·tcp/ip
南境十里·墨染春水8 小时前
linux学习进展 shell编程
linux·运维·学习
goyeer8 小时前
【ITIL4】32服务实践 - 问题管理(Problem Management)
linux·运维·服务器·企业数字化·it管理·itil·it治理
怀旧,9 小时前
【Linux网络编程】8. 网络层协议 IP
linux·网络·tcp/ip
RH2312119 小时前
2026.5.12 Linux
java·linux·数据结构
cen__y9 小时前
Linux11(网络编程)
linux·运维·服务器·c语言·网络·网络协议·tcp/ip
ITKEY_9 小时前
archlinux x11桌面 部分程序识别成Wayland
linux