>>在不同的变量/数组中存储/捕获stdout和stderr(bash)

时间:2016-04-16 10:03:18

标签: linux bash

我们的想法是将STDOUT和STDERR转发到变量/数组,以创建将其记录在文件中的可能性。 特别是应记录STDERR。

向TheConstructor求助,我找到了一个解决方案,我认为它应该适用于每种情况......

< Store / Capture stdout and stderr in different variables (bash)>

我的bash不支持:

readarray
typeset: t_err

我的bash版本:

bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
Copyright (C) 2007 Free Software Foundation, Inc.

我的想法:

function CMD() {
  unset t_std t_err
  eval "$( ($1 ; $1 >&2) 2> >(readarray -t t_err; typeset -p t_err) > >(readarray -t t_std; typeset -p t_std) )"
}
CMD "cp  x.txt new_x.txt"
CMD "nocommand new_x.txt"

这些是bash给出的错误:

./test_files.sh: line 61: readarray: command not found
./test_files.sh: line 61: typeset: t_err: not found

1 个答案:

答案 0 :(得分:0)

  

我的想法是将STDOUT和STDERR转发到变量/数组,转换为   创建将其记录在文件中的可能性

为什么重新发明轮子?输出到文件比变量简单得多。

cp x.txt new_x.txt 1> out.txt 2> err.txt

如果你想在变量中存储stdout和stderr,并且你有Bash版本3,你是否尝试过第二个解决方案by @Constructor

unset t_std t_err
# REPLACE "echo std; echo err >&2" with your real command
eval "$( (echo std; echo err >&2 ) 2> >(t_err=$(cat); typeset -p t_err) > >(t_std=$(cat); typeset -p t_std) )"

另请参阅further topic development in the answer of @BinaryZebra

相关问题