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内核构建三剑客:Kconfig、.config与Makefile关系详解
linux·makefile·kconfig·.config
轩轶子6 分钟前
【Macbook环境配置】Macbook设置ssh免密登陆服务器
运维·服务器·ssh
Dillon Dong7 分钟前
服务器运维:Linux 磁盘查看 & 清理常用命令
linux·运维·服务器
ben9518chen12 分钟前
Linux用户管理
linux·运维·服务器
m0_7373025830 分钟前
云服务器的多元形态进化史
服务器
root666/1 小时前
【后端开发-nginx】proxy_pass和proxy_redirect参数作用
运维·nginx
用户6135411460161 小时前
xampplinux_v174beta11在 Linux 下的安装与配置步骤
linux
Byron Loong1 小时前
【系统】Mac系统和Linux 指令对比
linux·macos·策略模式
DO your like1 小时前
手机热点搭建个人局域网
服务器·智能手机·智能路由器
markvivv1 小时前
在 Kylin Linux Advanced Server for Kunpeng V10 上构建 VSCode 1.106
linux·vscode·kylin