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 
$
相关推荐
鸠摩智首席音效师5 小时前
linux 系统中 Shutting Down, Restarting, Halting 有什么区别 ?
linux·运维·服务器
CIb0la5 小时前
Linux 将继续不支持 HDMI 2.1 实现
linux·运维·服务器
吕了了6 小时前
85 微PE吕了了修改版--更新!
运维·windows·电脑·系统
德生coding6 小时前
wifi驱动编译出来的驱动文件怎么做strip
linux
鹿鸣天涯6 小时前
Kali Linux 2025.4 发布:桌面环境增强,新增 3 款安全工具
linux·运维·安全
峥嵘life7 小时前
Android16 EDLA 认证测试CTS问题分析解决
android·java·服务器
学习&笔记7 小时前
MTK(系统篇)user版本无法使用setenforce 0命令关闭selinux权限
linux·运维·服务器
Bdygsl7 小时前
Linux(8)—— 进程优先级与环境变量
linux·运维·服务器
another heaven7 小时前
【软考 磁盘磁道访问时间】总容量等相关案例题型
linux·网络·算法·磁盘·磁道
吕了了7 小时前
87 Windows 系统安装的本质是什么?
运维·windows·电脑·系统