为什么超时在 bash 脚本中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22714787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does timeout not work within a bash script?
提问by user657592
I tried to kill a process if it exceeds more than a few seconds.
如果进程超过几秒钟,我试图杀死它。
The following works just fine when I run it in the terminal.
当我在终端中运行它时,以下工作正常。
timeout 2 sleep 5
But when I have a script -
但是当我有剧本时——
#!/bin/bash
timeout 2 sleep 5
it says
它说
timeout: command not found
超时:找不到命令
Why so? What is the workaround?
为什么这样?解决方法是什么?
--EDIT--
- 编辑 -
On executing type timeout, it says -
在执行类型超时时,它说 -
timeout is a shell function
timeout 是一个 shell 函数
回答by Rahul Patil
It's seems your environment $PATH
variable does not include /usr/bin/
path or may be timeout
binary exists in somewhere else.
您的环境$PATH
变量似乎不包含/usr/bin/
路径,或者可能是timeout
其他地方存在的二进制文件。
So just check path of timeout command using :
所以只需使用以下命令检查超时命令的路径:
command -v timeout
and use absolute path in your script
并在脚本中使用绝对路径
Ex.
前任。
#!/bin/bash
/usr/bin/timeout 2 sleep 5
Update 1#
更新1#
As per your update in question, it is function created in your shell. you can use absolute path in your script as mentioned in above example.
根据您有问题的更新,它是在您的 shell 中创建的函数。您可以在脚本中使用绝对路径,如上例所述。
Update 2#timeout
command added from coreutils version => 8.12.197-032bb
, If GNU timeout is not available you can use expect (Mac OS X, BSD, ... do not usually have GNU tools and utilities by default).
timeout
从 coreutils version => 添加的更新 2#命令8.12.197-032bb
,如果 GNU 超时不可用,您可以使用 expect(Mac OS X、BSD、...默认情况下通常没有 GNU 工具和实用程序)。
################################################################################
# Executes command with a timeout
# Params:
# timeout in seconds
# command
# Returns 1 if timed out 0 otherwise
timeout() {
time=
# start the command in a subshell to avoid problem with pipes
# (spawn accepts one command)
command="/bin/sh -c \"\""
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
}
Example:
例子:
timeout 10 "ls ${HOME}"