为什么超时在bash脚本中不起作用?

时间:2014-03-28 13:53:05

标签: linux bash timeout

如果超过几秒钟,我试图杀死一个进程。

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

timeout 2 sleep 5

但是当我有一个脚本时 -

#!/bin/bash
timeout 2 sleep 5

它说

  

超时:未找到命令

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

- 编辑 -

在执行类型超时时,它会显示 -

  

timeout是一个shell函数

1 个答案:

答案 0 :(得分:3)

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

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

command -v timeout

并在脚本中使用绝对路径

前。

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

更新1#

根据您的相关更新,它是在您的shell中创建的功能。您可以在脚本中使用绝对路径,如上例所示。

更新2# 从coreutils version =>添加的timeout命令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