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 
$
相关推荐
123过去4 小时前
wifi-honey使用教程
linux·网络·测试工具
志栋智能4 小时前
低成本自动化巡检:7×24小时守护业务稳定
运维·网络·自动化
ToB营销学堂5 小时前
MarketUP | B2B 自动化营销实战:如何打破“营-销”数据孤岛,构建高转化线索流?
运维·自动化
Deitymoon6 小时前
linux——孤儿进程和僵尸进程
linux
CDN3606 小时前
360CDN 全系列产品体验:CDN / 高防 / SDK 游戏盾横向测评
运维·安全·游戏
行者-全栈开发6 小时前
容器化时代来临 - Docker 技术演进与核心价值
运维·docker·容器·cicd·自动化构建·容器化时代
云飞云共享云桌面7 小时前
非标自动化研发成本高?云飞云共享云桌面:1台主机=10台工作站,年省数十万。
大数据·运维·服务器·人工智能·自动化·云计算·电脑
chehaoman7 小时前
Failed to restart nginx.service Unit nginx.service not found
运维·nginx
Linux运维技术栈7 小时前
生产环境Linux应用目录迁移至LVM独立分区 标准化实战方案
linux·运维·服务器·lvm·逻辑卷
feasibility.8 小时前
SSH Agent Forwarding 与 tmux 排障笔记
linux·运维·服务器·经验分享·笔记·ssh