gpt4 book ai didi

bash - 如何使用 Bash 读取超时?

转载 作者:行者123 更新时间:2023-11-29 08:40:03 25 4
gpt4 key购买 nike

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

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

我该怎么做?

最佳答案

bash(1) 中,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.

下面的文字记录(不按 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:

$ 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:

$ 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

(1) 如果您在脚本中执行此操作,请确保这是一个bash一。您可以通过在开头添加一个 shebang 行来做到这一点,例如以下之一:

#!/usr/bin/env bash
#!/bin/bash

关于bash - 如何使用 Bash 读取超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9483633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com