是否可以在不同的变量中存储或捕获 stdout 和 stderr,而不使用临时文件?现在我这样做是为了在运行 some_command
时在 out
中获取 stdout 并在 err
中获取 stderr,但我会
喜欢避免使用临时文件。
error_file=$(mktemp)
out=$(some_command 2>$error_file)
err=$(< $error_file)
rm $error_file
最佳答案
好的,它有点难看,但这里有一个解决方案:
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)
需要替换为实际命令。 stdout 的输出逐行保存到数组 $t_std
中,省略换行符(-t
)和 stderr 进入 $t_err
。
如果你不喜欢数组你可以这样做
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)
的行为,除了 $?
的值将我们带到最后修改:
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) .
关于bash - 将 stdout 和 stderr 捕获到不同的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11027679/