Save Bash Output to A File – Automatically

I often have a need to save the output a bash file to another file, e.g., log file. I know I could use redirection “>” or “tee”. But I would have to type it from command line. This post talk about doing it from within the script itself.

Google search does not yield much meaningful results. To save the hassle for me and potentially others. Here is the straight no-BS code.


readonly file="output"
exec 1> >(tee $file)
exec 2>&1