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 
$
相关推荐
冰橙子id3 小时前
linux-远程访问管理(sshd,scp,sftp)
linux·网络·ssh
光电的一只菜鸡4 小时前
ubuntu之坑(十五)——设备树
linux·数据库·ubuntu
saynaihe5 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
企鹅与蟒蛇5 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
小蜜蜂爱编程6 小时前
ubuntu透网方案
运维·服务器·ubuntu
程序设计实验室6 小时前
小心误关了NAS服务器!修改Linux的电源键功能
linux·nas
AI视觉网奇6 小时前
git 访问 github
运维·开发语言·docker
头发那是一根不剩了7 小时前
nginx:SSL_CTX_use_PrivateKey failed
运维·服务器
七夜zippoe7 小时前
破解 VMware 迁移难题:跨平台迁移常见问题及自动化解决方案
运维·自动化·vmware
hweiyu008 小时前
docker简介
运维·docker·容器