超时有效的命令和捕获输出到bash脚本变量 [英] Timeout a command efficiently and capture output to a variable in bash script
问题描述
我需要运行一个命令,运行时间太长的时候杀了它,在bash脚本。我还需要捕获所有的输出变量。如果命令完成第一,我需要释放/杀watchdog进程(例如睡眠),因为我可以运行这样的命令列表。
I need to run a command and kill it when running too long, in a bash script. I also need to capture all output to a variable. If the command finishes first, I need to release/kill the watchdog process (e.g. sleep) because I may run a list of such commands.
不幸的是,超时命令不能提供给我,othervise我可以做这样的事情:
Unfortunately the "timeout" command is not available to me, othervise I could do something like this:
output=`timeout -s 9 $TIMEOUT my-command`
和检查出code 124,看看是否有超时。
and check for the exit code 124 to see if there was a timeout.
所以我选择的解决方案是<一个href=\"http://stackoverflow.com/questions/687948/timeout-a-command-in-bash-without-unnecessary-delay\">by @Dmitry到类似的问题:
Therefore my solution of choice is by @Dmitry to a similar question:
( my_command ) & pid=$!
( sleep $TIMEOUT && kill -HUP $pid ) 2>/dev/null & watcher=$!
wait $pid 2>/dev/null && pkill -HUP -P $watcher
不幸的是,下列不捕获任何到$输出:
Unfortunately the following does not capture anything to the $output:
( output=`my_command` ) & pid=$!
我可以转储输出到一个文件,然后加载在这样的变量,但我宁可没有文件:
I could dump the output to a file and then load it in the variable like this, but I'd rather do without files:
( `my_command >$outfile` ) & pid=$!
...
output=`cat $outfile`
rm -f $outfile
我的问题:有没有更好的办法?理想的情况下捕捉标准错误,以及另一个变量,而无需使用文件?
My question: is there a better way? Ideally capturing the stderr as well to another variable without using files?
推荐答案
幸运的是, $()
标记允许多个命令,所以你可以这样做:
Fortunately, the $()
notation allows for multiple commands, so you can do this:
output=$(
( my_command ) & pid=$!
( sleep $TIMEOUT && kill -HUP $pid ) 2>/dev/null & watcher=$!
wait $pid 2>/dev/null && pkill -HUP -P $watcher
)
您也可以使用普通的()
来组命令,然后重定向所有的输出。重定向错误输出到标准输出可以用 2 - 来完成;&放大器; 1
,所以你最终这样的:
You can also use regular ()
to group commands and then redirect all their output. Redirecting stderr to stdout can be done using 2>&1
, so you end up with this:
output=$(
(
( my_command ) & pid=$!
( sleep $TIMEOUT && kill -HUP $pid ) 2>/dev/null & watcher=$!
wait $pid 2>/dev/null && pkill -HUP -P $watcher
) 2>&1
)
这篇关于超时有效的命令和捕获输出到bash脚本变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!