1

The idea was to forward STDOUT and STDERR to a variable/array, to create the possibility to log it in a file. Especially STDERR should be logged.

Thks to TheConstructor, I found a solution I thougth it should work in every case ...

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

My bash doesn't support :

readarray
typeset: t_err

my version of bash :

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

my thought :

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"

these are the errors given by the bash :

./test_files.sh: line 61: readarray: command not found
./test_files.sh: line 61: typeset: t_err: not found
Community
  • 1
  • 1
kris
  • 392
  • 4
  • 16
  • 3
    I don't think `readarray` was introduced until bash 4, which would explain why you get `command not found` for it with your bash 3 – Eric Renouf Apr 16 '16 at 11:27

1 Answers1

1

The idea was to forward STDOUT and STDERR to a variable/array, to create the possibility to log it in a file

Why reinvent a wheel? To output to a file is much simpler than to variable.

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


If you want to store both stdout and stderr in variables, and you have Bash version 3, have you tried the second solution 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) )"

Also, see further topic development in the answer of @BinaryZebra.

Community
  • 1
  • 1
John_West
  • 2,239
  • 4
  • 24
  • 44