1

I have a small test script here, it has error handling. I would like all STDERR and STDOUT to be displayed on the console (which they currently are) AND made into a log file.

#!/bin/bash

# error handling
function error_handler() {
  echo "Error occurred in script at line: ${1}."
  echo "Line exited with status: ${2}"
}

trap 'error_handler ${LINENO} $?' ERR

set -o errexit
set -o errtrace
set -o nounset

if rsync -aPh ~/Downloads/Temps-linux-x64.zip .; then
        echo "SUCCESSFULL rsync of files"
else
        echo "FAILED rsync of files"
fi

I have tried to trap it by adding this to the start;

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>log.out 2>&1

but this (as it's supposed to) logs everything but has no output to the console. It's also causing the error handling to not work correctly so I need another solution.

eekfonky
  • 665

2 Answers2

2

You can use descriptor redirection to a coproc

#!/bin/bash 
exec 3<&1
coproc mytee { tee log.out >&3;  }
exec >&${mytee[1]} 2>&1

... your script ...

STDOUT and STDERR will be merged in the script output. It would be nice someone found a way to have them merged in the log file but separated in the output.

Emmanuel
  • 4,187
0

Use tee:

./script 2>&1 | tee log.out

tee copies standard input to standard output and to any specified file(s); in the example above this is log.out. For more info, see man tee.

countermode
  • 7,533
  • 5
  • 31
  • 58
pfnuesel
  • 5,837