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

5

如果一个进程超过几秒钟,我尝试杀掉它。

当我在终端中运行以下命令时,它可以完美地工作。

timeout 2 sleep 5

但是当我有一个脚本时 -
#!/bin/bash
timeout 2 sleep 5

它显示

超时:找不到命令

为什么会这样?有什么解决方法吗?

--编辑--

在执行type timeout时,它说 -

timeout是一个shell函数


如果在 shell 中运行 type timeout,你会得到什么? - Reinstate Monica Please
@user657592 你使用的是哪个bash版本?还要检查一下/usr/bin/timeout是否存在。 - Rahul Patil
@BroSlow - 一样的。timeout是一个shell函数 - user657592
@user657592,您能提供您正在使用的coreutils版本吗?请使用命令rpm -qa | grep coreutil进行查询。如果版本号小于coreutils 8.12.197-032bb,那么可能是函数创建的问题,您需要更新coreutils并使用timeout二进制文件。 - Rahul Patil
需要更新coreutils软件包 => coreutils 8.12.197-032bb - Rahul Patil
显示剩余5条评论
1个回答

5

看起来你的环境变量$PATH中不包含/usr/bin/路径,或者timeout二进制文件存在于其他地方。

因此,只需使用以下命令检查timeout命令的路径:

command -v timeout

请在您的脚本中使用绝对路径

例如:

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

更新1#

根据您在问题中的更新,这是在您的shell中创建的函数。您可以像上面的示例一样在脚本中使用绝对路径。

更新2# timeout命令从coreutils版本8.12.197-032bb开始添加,如果GNU timeout不可用,则可以使用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是否存在。 - Rahul Patil
使用绝对路径也没有帮助。然后它说 - /usr/bin/timeout:找不到文件或目录 - user657592
在你的脚本中,开头处 - Rahul Patil
现在它显示了这个 - 启动AutoMATCH程序 调用Main-dispatch-ex程序 文件名: - user657592

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接