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.

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.

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.

  • Thank you, is there a way to incorporate it into the script though? – eekfonky Nov 14 '16 at 12:43
  • @eekfonky You can add the same command at the end of your echo statements. – pfnuesel Nov 14 '16 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.