如何使用Bash读取超时? [英] How to use Bash read with a timeout?

查看:87
本文介绍了如何使用Bash读取超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以要求用户使用read按下 Enter ,然后通过调用sleep让他等待.但是我想不出同时做这两种方式的方法.我希望为用户提供选择:

I can ask the user to press Enter by using read, and have him wait by calling sleep. But I can’t think of a way of doing both at the same time. I would like the user to be given the choice:

Ctrl + C 取消,按 Enter 继续或仅等待10秒

Press Ctrl+C to Cancel, Enter to continue or just wait 10 seconds

我该怎么办?

推荐答案

bash中,read具有-t选项,您可以在其中指定超时.在联机帮助页上:

In bash, read has a -t option where you can specify a timeout. From the manpage:

read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...]

-t timeout: 导致读取超时,如果在超时秒内未读取完整的输入行,则返回失败.如果读取未读取来自终端或管道的输入,则此选项无效.

-t timeout: cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe.

下面的成绩单(不按ENTER):

Transcript below (without hitting ENTER):

$ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; echo ; date
Tue Feb 28 22:29:15 WAST 2012
Hit ENTER or wait ten seconds
Tue Feb 28 22:29:25 WAST 2012

另一个,几秒钟后按ENTER键:

Another, hitting ENTER after a couple of seconds:

$ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; date
Tue Feb 28 22:30:17 WAST 2012
Hit ENTER or wait ten seconds
Tue Feb 28 22:30:19 WAST 2012

然后按下CTRL-C:

And another, hitting CTRL-C:

$ date ; read -t 10 -p "Hit ENTER or wait ten seconds" ; echo ; date
Tue Feb 28 22:30:29 WAST 2012
Hit ENTER or wait ten seconds

这篇关于如何使用Bash读取超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆