Write output to both log.out and console

I have a basic build script that I want to log its entire output to a log file. Example

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>log.out 2>&1
echo "Run Date: $(date)"
echo "another line"
conda -V

With this the console remains blank and everything is saved to the log.out This works great for me but I would also like it to still print everything to the console as well.

Essentially, I want it to mimic the behavior of

echo "Run Date: $(date)" 2>&1 | tee -a log.out
echo "another line"  2>&1 | tee -a log.out
conda -V 2>&1 | tee -a log.out

without having to type 2>&1 | tee -a log.out at the end of every line.


Solution 1:

You could do this by enclosing all your commands in a code block and redirecting the output of the entire block. You'd still have to contend with the redirection syntax but it would only be in one place:

{
    echo "Run Date: $(date)"
    echo "another line"
    conda -V
} 2>&1 | tee -a log.out

Solution 2:

You could group all your commands and capture that output to a log with tee:

#!/bin/bash

{
    echo "duck"
    echo "duck"
    echo "goose" >>/dev/stderr
    echo "Run Date: $(date)"
} 2>&1 |tee -a log.out

.... or just have the script output to stdout/stderr as it would without the redirects, and capture that output on whatever launches the script? ./test.sh 2>&1 |tee -a log.out