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 
$
相关推荐
好好学习天天向上~~14 分钟前
6_Linux学习总结_自动化构建
linux·学习·自动化
REDcker14 分钟前
gRPC开发者快速入门
服务器·c++·后端·grpc
冉佳驹21 分钟前
Linux ——— 静态库和动态库的设计与使用
linux·动态库·静态库·fpic
陌上花开缓缓归以42 分钟前
linux mtd-utils使用源码分析(ubuntu测试版)
linux·arm开发·ubuntu
江湖有缘1 小时前
零基础入门:使用 Docker 快速部署 Organizr 个人主页
java·服务器·docker
wangjialelele1 小时前
Linux下的IO操作以及ext系列文件系统
linux·运维·服务器·c语言·c++·个人开发
HypoxiaDream2 小时前
LINUX-Ext系列⽂件系统
linux·运维·服务器
小毛驴8502 小时前
Linux curl 命令用法
linux·运维·chrome
李斯啦果2 小时前
【Linux】Linux目录配置
linux·运维·服务器
AI+程序员在路上2 小时前
linux下线程中pthread_detach与pthread_join区别
linux·运维·服务器