问题描述
是否可以在不使用临时文件的情况下在不同变量中存储或捕获stdout和stderr?现在,我这样做是为了在运行some_command
时在out
中获得stdout,在err
中获得stderr,但是我想想要避免使用临时文件.
Is it possible to store or capture stdout and stderr in different variables, without using a temp file? Right now I do this to get stdout in out
and stderr in err
when running some_command
, but I'dlike to avoid the temp file.
error_file=$(mktemp)
out=$(some_command 2>$error_file)
err=$(< error_file)
rm $error_file
推荐答案
好的,这有点丑陋,但这是一个解决方案:
Ok, it got a bit ugly, but here is a solution:
unset t_std t_err
eval "$( (echo std; echo err >&2) \
2> >(readarray -t t_err; typeset -p t_err) \
> >(readarray -t t_std; typeset -p t_std) )"
其中,(echo std; echo err >&2)
需要用实际命令替换.通过将换行(-t
)和 stderr 省略到$t_err
中,将 stdout 的输出保存到数组$t_std
行中.
where (echo std; echo err >&2)
needs to be replaced by the actual command. Output of stdout is saved into the array $t_std
line by line omitting the newlines (the -t
) and stderr into $t_err
.
如果您不喜欢数组,可以这样做
If you don't like arrays you can do
unset t_std t_err
eval "$( (echo std; echo err >&2 ) \
2> >(t_err=$(cat); typeset -p t_err) \
> >(t_std=$(cat); typeset -p t_std) )"
几乎模仿了var=$(cmd)
的行为,除了$?
的值使我们进行了最后修改:
which pretty much mimics the behavior of var=$(cmd)
except for the value of $?
which takes us to the last modification:
unset t_std t_err t_ret
eval "$( (echo std; echo err >&2; exit 2 ) \
2> >(t_err=$(cat); typeset -p t_err) \
> >(t_std=$(cat); typeset -p t_std); t_ret=$?; typeset -p t_ret )"
$?
保留在$t_ret
使用 GNU bash
,版本 4.2.37(1)-release(i486-pc-linux-gnu)在Debian wheezy上进行了测试.
Tested on Debian wheezy using GNU bash
, Version 4.2.37(1)-release (i486-pc-linux-gnu).
这篇关于将stdout和stderr捕获到不同的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!