将 stdout 和 stderr 捕获到不同的变量中 [英] Capture stdout and stderr into different variables
问题描述
是否可以在不使用临时文件的情况下在不同变量中存储或捕获标准输出和标准错误?现在我这样做是为了在运行 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'd
like 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) )"
where (echo std; echo err >&2)
需要替换为实际的命令.stdout 的输出逐行保存到数组 $t_std
中,省略换行符(-t
)和 stderr 进入$t_err
.
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
在 Debian wheezy 上测试,版本 4.2.37(1)-release (i486-pc-linux-gnu).
Tested on Debian wheezy using GNU bash
, Version 4.2.37(1)-release (i486-pc-linux-gnu).
这篇关于将 stdout 和 stderr 捕获到不同的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!