Fabricator Fabricator - 28 days ago 7
Linux Question

Redirect stdout and stderr to file and stderr to stdout

The following writes stdout to a logfile and prints stderr:

bash script.sh >> out.log


This again writes both stdout and stderr to a logfile:

bash script.sh >> out.log 2>&1


How to combine both features, so that stdout and stderr are logged to a file and stderr is emailed to my inbox?

Answer
bash script.sh 2>&1 >> out.log | tee -a out.log

First, I'm redirecting stdout to file and stderr to stdout (stdout line gets to the out.log file and stderr to pipe).

The tee command prints stdin to both stdout and file (resemblance with the letter T). Thus second, I'm printing the original stderr to both stdout and the out.log file (the -a argument means append).