brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: exec with tee logs everything a shell script prints

Shell
~/tips/tip-shell-exec-tee-script-log

exec > >(tee -a /var/log/nightly.log) 2>&1

Send all output of a script to a log file while you still see it on screen.

Adding | tee to every line of a script gets old fast. One exec line at the top does it for the whole script.

When exec gets no command, it only applies its redirections to the current shell. Combine that with process substitution and every line after it goes through tee:

#!/usr/bin/env bash
exec > >(tee -a /var/log/nightly.log) 2>&1

echo "backup started"
rsync -a /srv/data/ /mnt/backup/data/

The first part sends stdout into tee, which appends to the log and also prints to your terminal. The 2>&1 after it points stderr at the same place, so error messages land in the log too. That order matters: put 2>&1 first and stderr still goes to the old stdout.

I like this for scripts that run from cron and by hand. From cron the copy on screen ends up in the cron mail or nowhere, and the log file has it all either way.

One thing to know: tee runs as a separate process, so the script can exit a moment before the last lines reach the file. If something reads the log straight after the script ends, add a short sleep 1 at the end or check the file a bit later. Process substitution is a bash feature, so plain sh will refuse this line.

Further reading: Bash manual: Redirections, Bash manual: Process Substitution

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link