Only redirecting to the $OUT file in append mode is much easier:
case $TERM_OPT in
(OFF) exec >> "$OUT";;
(*) exec > >(tee -ia -- "$OUT")
esac
Beware the shell doesn't wait for tee upon exiting, so you might find that tee is still outputting something after your script has finished.
$ bash -c 'exec > >(tee -ia -- file); echo A'; echo B; sleep 1
B
A
See how A was output after B.
To work around that, you can add:
if [ "$TERM_OPT" != OFF ]; then
exec > /dev/null # closes the pipe to tee which should cause tee
# to see EOF on input and exit
wait # waits for all asynchronous tasks including tee
fi
At the end of the script or in an EXIT trap.
Another option (which would also work in sh) is to put your whole script inside a main function and do:
#! /bin/sh -
main() {
# your script here
}
case $TERM_OPT in
(OFF) main "$@" >> "$OUT";;
(*) main "$@" | tee -ia -- "$OUT"
esac