【问题标题】:Why does timeout not work within a bash script?为什么超时在 bash 脚本中不起作用?
【发布时间】:2014-03-28 13:53:05
【问题描述】:

如果某个进程超过几秒钟,我会尝试终止它。

当我在终端中运行它时,以下工作正常。

timeout 2 sleep 5

但是当我有一个脚本时 -

#!/bin/bash
timeout 2 sleep 5

它说

超时:找不到命令

为什么会这样?解决方法是什么?

--编辑--

在执行类型超时时,它说 -

超时是一个shell函数

【问题讨论】:

  • 如果在 shell 中运行 type timeout 会得到什么?
  • @user657592 您使用的是哪个 bash 版本?并检查/usr/bin/timeout是否存在
  • 如果你运行type -a timeout,你会得到唯一的timeout吗?通常,如果您在某个地方实现了该函数以在脚本中使用它,则需要导出该函数,但就像@RahulPatil 提到的超时通常只是一个 c 函数,除非您有其他一些实现。
  • @BroSlow - 一样。 timeout is a shell function
  • @user657592 将export -f timeout 添加到您的.bashrc 或您实施的任何位置。然后重新获取该初始化文件(例如使用source .bashrc)并尝试再次运行脚本。

标签: linux bash timeout


【解决方案1】:

您的环境$PATH 变量似乎不包含/usr/bin/ 路径,或者可能是timeout 二进制文件存在于其他地方。

所以只需使用以下命令检查超时命令的路径:

command -v timeout

并在脚本中使用绝对路径

例如

#!/bin/bash
/usr/bin/timeout 2 sleep 5

更新 1#

根据您的更新,它是在您的 shell 中创建的函数。如上例所述,您可以在脚本中使用绝对路径。

更新 2# timeout 从 coreutils 版本添加的命令 => 8.12.197-032bb,如果 GNU 超时不可用,您可以使用 expect(Mac OS X、BSD ......通常默认情况下没有 GNU 工具和实用程序)。

################################################################################
# Executes command with a timeout
# Params:
#   $1 timeout in seconds
#   $2 command
# Returns 1 if timed out 0 otherwise
timeout() {

    time=$1

    # start the command in a subshell to avoid problem with pipes
    # (spawn accepts one command)
    command="/bin/sh -c \"$2\""

    expect -c "set echo \"-noecho\"; set timeout $time; spawn -noecho $command; expect timeout { exit 1 } eof { exit 0 }"    

    if [ $? = 1 ] ; then
        echo "Timeout after ${time} seconds"
    fi

}

示例:

timeout 10 "ls ${HOME}"

Source

【讨论】:

  • 您使用的是哪个 bash 版本?并检查/usr/bin/timeout是否存在
  • 使用绝对路径没有帮助。然后它说 - /usr/bin/timeout: No such file or directory found
  • 在你的脚本中,在开头
  • 现在,它这样说 - Starting AutoMATCH program alling Main-dispatch-ex program filename:
猜你喜欢
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
  • 2014-01-04
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多