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 
$
相关推荐
深耕AI1 小时前
【完整教程】宝塔面板FTP配置与FileZilla连接服务器
运维·服务器
serve the people1 小时前
Prompts for Chat Models in LangChain
java·linux·langchain
李昊哲小课2 小时前
Ubuntu 24.04 MariaDB 完整安装与配置文档
linux·ubuntu·mariadb
无聊的小坏坏2 小时前
从单 Reactor 线程池到 OneThreadOneLoop:高性能网络模型的演进
服务器·网络·一个线程一个事件循环
AI智域边界 - Alvin Cho3 小时前
Bloomberg、LSEG 与 MCP 缺口:为什么尚未发布完整的 MCP 服务器,以及多智能体系统如何解決这问题
运维·服务器
人间打气筒(Ada)3 小时前
zerotier内网穿透部署(rockylinux部署本地服务器)超详细~~~
linux·内网穿透·内网·公网·zerotier·穿透
Elias不吃糖4 小时前
Git常用指令合集
linux·git
_OP_CHEN4 小时前
Linux网络编程:(七)Vim 编辑器完全指南:从入门到精通的全方位实战教程
linux·运维·服务器·编辑器·vim·linux生态·linux软件
Maple_land4 小时前
第1篇:Linux工具复盘上篇:yum与vim
linux·运维·服务器·c++·centos
shizhan_cloud4 小时前
Linux 硬盘分区管理
linux·运维