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: set -x with a better PS4 shows the line number of every traced command

Shell
~/tips/tip-bash-set-x-ps4-line-numbers

set -x

Shows the file and line number in front of every command bash traces with set -x.

When a bash script does something odd, set -x is the quickest way to watch it work: bash prints every command, with the variables already filled in, before it runs it. The default output starts each line with a plain +, though, and in a script of a few hundred lines that leaves you guessing where you are.

Bash prints the value of the PS4 variable in front of every traced line, and you can put the file name and line number in it:

#!/bin/bash
PS4='+ ${BASH_SOURCE}:${LINENO}: '
set -x

src=/mnt/user/appdata/myapp
rsync -a "$src/" /mnt/user/backup/myapp/

Run it and the trace looks like this:

+ ./backup.sh:5: src=/mnt/user/appdata/myapp
+ ./backup.sh:6: rsync -a /mnt/user/appdata/myapp/ /mnt/user/backup/myapp/

Now every line tells you exactly where it came from, and with BASH_SOURCE that still works when your script sources a second file. Use single quotes around the PS4 value. With double quotes, the line number is filled in once, when you set the variable, and every trace line shows the same number. My advice is to trace only the part you’re unsure about: put set -x just above it and set +x right after.

Two things to watch out for. The trace goes to stderr, so a cron job that saves its output keeps all of it in the log. And the trace shows variables after expansion, so a password or API token in a curl line ends up in that log in plain text. If you want the trace somewhere else, bash has BASH_XTRACEFD: point it at a file descriptor you opened, and the set -x output goes there instead of stderr.

Further reading: bash(1) manual page

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