How do you redirect all output of an entire script to a log file while still seeing it?
IntermediateConceptArguments, I/O, here-docs, process substitution and subshells
Answer
log=/var/log/deploy/deploy-$(date +%F).log
exec > >(tee -a "$log") 2>&1
echo "this goes to the terminal and the log"
exec with only redirections applies them to the rest of the script. A caveat: tee runs asynchronously, so the last lines may appear after the shell prompt returns. Under systemd, skip this and just write to stdout/stderr; journald captures it with timestamps.
More on Arguments, I/O, here-docs, process substitution and subshells
How does `getopts` work? Show a complete example.IntermediateWhat is the difference between `getopts` and `getopt`?AdvancedExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?Intermediate