use*_*592 4 linux bash timeout
如果进程超过几秒钟,我试图杀死它。
当我在终端中运行它时,以下工作正常。
timeout 2 sleep 5
Run Code Online (Sandbox Code Playgroud)
但是当我有剧本时——
#!/bin/bash
timeout 2 sleep 5
Run Code Online (Sandbox Code Playgroud)
它说
超时:找不到命令
为什么这样?解决方法是什么?
- 编辑 -
在执行类型超时时,它说 -
timeout 是一个 shell 函数
您的环境$PATH
变量似乎不包含/usr/bin/
路径,或者可能是timeout
其他地方存在的二进制文件。
所以只需使用以下命令检查超时命令的路径:
command -v timeout
Run Code Online (Sandbox Code Playgroud)
并在脚本中使用绝对路径
前任。
#!/bin/bash
/usr/bin/timeout 2 sleep 5
Run Code Online (Sandbox Code Playgroud)
更新1#
根据您有问题的更新,它是在您的 shell 中创建的函数。如上例所述,您可以在脚本中使用绝对路径。
timeout
从 coreutils version => 添加的更新 2#命令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
}
Run Code Online (Sandbox Code Playgroud)
例子:
timeout 10 "ls ${HOME}"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15058 次 |
最近记录: |