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 
$
相关推荐
IT 小阿姨(数据库)3 分钟前
PostgreSQL pg_stat_bgwriter 视图各个字段详解
linux·数据库·sql·postgresql·centos
风语者日志40 分钟前
[LitCTF 2023]Vim yyds
linux·编辑器·vim
Thexhy1 小时前
在centos 7上配置FIP服务器的详细教程!!!
linux·运维·centos
chao1898441 小时前
C 文件操作全解速览
服务器·c语言·c#
FJW0208141 小时前
DevOps——CI/CD持续集成与持续交付/部署的理解与部署
运维·ci/cd·devops
Java 码农2 小时前
Linux shell sed 命令基础
linux·运维·服务器
yong15858553432 小时前
1. Linux C++ muduo 库学习——库的编译安装
linux·c++·学习
fyakm2 小时前
Linux网络接口配置:静态IP与动态IP设置(附代码示例)
linux·运维·tcp/ip
怀旧,2 小时前
【Linux系统编程】5. 基础开发⼯具(下)
linux·运维·服务器
喵叔哟2 小时前
10. 从0到上线:.NET 8 + ML.NET LTR 智能类目匹配实战--Web API 接口与前端集成:部署与生产运维:稳定性、可观测与成本
运维