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 
$
相关推荐
Fortune_yangyang17 小时前
Docker 入门指南:从 “容器小白” 到快速上手
运维·docker·容器
Lueeee.17 小时前
具体掌握字符设备驱动
linux
HIT_Weston18 小时前
68、【Ubuntu】【Hugo】搭建私人博客:方案分析(二)
linux·运维·ubuntu
wdfk_prog18 小时前
[Linux]学习笔记系列 -- [fs]ext4
linux·笔记·学习
程序员老舅18 小时前
C++ STL 算法:从原理到工程实践
linux·c++·stl·c/c++·数据结构与算法
chenyuhao202418 小时前
Linux系统编程:线程概念与控制
linux·服务器·开发语言·c++·后端
cws20040119 小时前
HeidiSQL 使用操作说明书
运维·数据库·windows·mysql·heidisql
Pyeako19 小时前
MySQL基础知识&Linux导入导出数据
linux·数据库·mysql·sql查询·sql分类
prettyxian19 小时前
【linux】进程概念(1)PCB、系统调用与 proc 目录全解析
linux·运维·服务器
YJlio19 小时前
Streams 学习笔记(12.2):看见 NTFS 隐藏的备用数据流(ADS)
服务器·笔记·学习