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: BASH_XTRACEFD sends set -x output of a bash script to its own file

Bash
~/tips/tip-bash-xtracefd-trace-file

set -x

Keep trace lines out of the normal error output of a script.

set -x is great for seeing what a script does, but its lines go to stderr and mix with the real error messages. Bash can send the trace somewhere else.

Open a file on a free descriptor and tell bash to use it for tracing:

exec 5>/tmp/deploy-trace.log
BASH_XTRACEFD=5
set -x

rsync -a ./site/ /var/www/site/
systemctl reload nginx

The terminal shows only the normal output and errors. Every traced command, with its expanded arguments, lands in the trace file, where you can read it at your own pace.

I find this works nicely with a custom PS4 that adds line numbers, and in scripts that run from cron, where you want the trace stored but the mail clean.

Two cautions. The trace shows variables after expansion, so passwords and tokens passed as arguments end up in that file in plain text; give it tight permissions or switch tracing off around those lines with set +x. And leave stderr out of it: the manual warns that setting BASH_XTRACEFD to 2 and then unsetting it closes stderr altogether. It arrived in bash 4.1, which leaves out the old macOS bash.

Further reading: Bash manual: Bash Variables (BASH_XTRACEFD)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link