Trace with bash -x and PS4
Execution tracing displays commands after expansions, making argument and control-flow mistakes easier to see. bash -x script.sh enables tracing for a child Bash; set -x and set +x enable and disable it within a script. By default trace goes to stderr, not stdout. PS4 supplies the trace prefix; single-quote a prefix containing $LINENO if it should expand when each trace line is emitted. set -v prints source lines as they are read, which is not the same as the expanded execution trace. BASH_XTRACEFD routes trace to an open descriptor; unsetting it closes that descriptor, so never casually assign descriptor 2. Traces can expose secrets, expanded arguments and paths. Use only synthetic data and keep trace files private. Structured diagnostics such as printf 'level=error step=parse status=%s\n' "$rc" >&2 can be a better production interface than tracing. Capture rc before logging; avoid logging sensitive input. The file-based examples set umask 077 before creating trace files in a fresh private directory. This restricts newly created files, not pre-existing ones. Disabling xtrace does not remove previously written data.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Trace a child script
umask 077cat > demo.sh <<'END' || exit 1label=demoprintf '%s\n' "$label"ENDbash -x demo.sh > out.txt 2> trace.txt || exit 1cat out.txt || exit 1[[ -s trace.txt ]] && printf 'trace recorded\n' Expected stdout:
demotrace recordedThe trace and data are saved independently.
Limit tracing to a small region
PS4='TRACE: 'set -xname=demoset +xprintf '%s\n' "$name"Expected stdout:
demoExpected stderr:
TRACE: name=demoTRACE: set +xThe prefix identifies trace lines. The final printf is outside tracing.
Route trace to an owned file
umask 077exec 3> trace.txt || exit 1BASH_XTRACEFD=3PS4='TRACE: 'set -xprintf 'data\n'set +xunset BASH_XTRACEFD[[ -s trace.txt ]] && printf 'trace saved\n' Expected stdout:
datatrace savedDescriptor 3 is dedicated to the trace; unsetting BASH_XTRACEFD closes it.
Common mistakes
Do not trace authentication, tokens or real confidential inputs. Do not compare the exact trace quoting across versions. Turning off tracing itself can appear in the trace. Do not close stderr by assigning and unsetting BASH_XTRACEFD=2.
Practice
Trace a fixed function that prints a synthetic label with spaces. Save stdout and stderr separately, identify the expanded arguments, then disable tracing and confirm normal output is unchanged.
Next: ShellCheck and shfmt