如何使用 Bash 读取超时? [英] How to use Bash read with a timeout?
问题描述
我可以使用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:
如果在 timeout 秒内没有读取完整的输入行,则导致读取超时并返回失败.如果 read 不是从终端或管道读取输入,则此选项无效.
-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.
下面的成绩单(不按回车键):
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屋!