【问题标题】:Shell Script (bash/ksh): 20 seconds to read a variableShell 脚本 (bash/ksh):读取一个变量需要 20 秒
【发布时间】:2010-09-24 11:07:00
【问题描述】:

我需要等待输入 20 秒,然后 myscript 应该会继续执行。
我试过使用 read -t20 var 但这仅适用于 bash。我在 Solaris 10 上使用 ksh。

有人可以帮帮我吗?

编辑:20 秒只是一个例子。让我们假设它需要等待 1 小时。但是这个人可以或不能在PC前面写输入,他不需要等待1个小时来输入输入,但是如果他不在PC前面,那么shell应该在等待后继续执行一段时间。

谢谢!

【问题讨论】:

  • sleep 20 && read ${variable}??
  • 20 秒只是一个例子。让我们假设它需要等待 1 小时。但是这家伙在电脑前写输入,他不需要等待 1 小时....明白了吗?

标签: bash unix ksh solaris-10 shell


【解决方案1】:

来自man ksh

TMOUT
如果设置为大于零的值,则如果在发出 PS1 提示后的规定秒数内未输入命令,则 shell 将终止。可以使用此值的最大限制来编译 shell。

我不确定这是否适用于 Solaris 上的 ksh 中的 read。它确实适用于 ksh93,但该版本也有 read -t

This script 包含这种方法:

# Start the (potentially blocking) read process in the background

    (read -p && print "$REPLY" > "$Tmp") &  readpid=$!

    # Now start a "watchdog" process that will kill the reader after
    # some time:

    (
        sleep 2; kill $readpid >/dev/null 2>&1 ||
        { sleep 1; kill -1 $readpid >/dev/null 2>&1; } ||
        { sleep 1; kill -9 $readpid; }
    ) &     watchdogpid=$!

    # Now wait for the reading process to terminate. It will terminate
    # reliably, either because the read terminated, or because the
    # "watchdog" process made it terminate.

    wait $readpid

    # Now stop the watchdog:

    kill -9 $watchdogpid >/dev/null 2>&1

    REPLY=TERMINATED            # Assume the worst
    [[ -s $Tmp ]] && read < "$Tmp"

【讨论】:

  • TMOUT 用于交互式会话,因此它显示为after issuing the PS1 prompt。它不会在脚本中做任何事情
  • @Daenyth:它在我尝试过的测试脚本中工作(但如果超时,它会使终端处于-echo 状态,我必须进行重置)。
【解决方案2】:

this forum thread第三帖就有答案了。

【讨论】:

  • 感谢伙计,它成功了。我想知道......既然我们使用的是 ksh,有没有办法用 coproccess 做到这一点?
  • 第三个帖子有read -t OP 无法使用。除非您不计算该链接上的问题,否则第三个 answer 不是解决方案。这种混淆是 SO 首选在您的答案中包含来自链接的信息的原因之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多