如何使用 Bash 读取超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9483633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:42:56  来源:igfitidea点击:

How to use Bash read with a timeout?

bashiotimeout

提问by qdii

I can ask the user to press Enterby 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:

我可以要求用户按Enter使用read,并通过调用让他等待sleep。但我想不出同时做这两件事的方法。我希望用户有以下选择:

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

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

How can I?do that?

我怎样才能做到这一点?

回答by paxdiablo

In bash, readhas a -toption where you can specify a timeout. From the manpage:

bash,read有一个-t选项,您可以在其中指定超时。从联机帮助页:

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

-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.

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

-t timeout:如果在超时秒内未读取完整的输入行,则会导致读取超时并返回失败。如果 read 不是从终端或管道读取输入,则此选项无效。

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

Another, hitting ENTER after a couple of seconds:

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

$ 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

And another, hitting CTRL-C:

另一个,按 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

回答by Johannes Weiss

The readbuiltin has a timeout.

read内置有超时。

read -t 10

will do it

会做的

回答by Benoit

From the bash reference manual:

bash 参考手册

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

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