Debugging Bash Scripts with set -x
Bash’s xtrace mode (-x) prints each command to stderr before executing it, making it the fastest way to trace script flow, inspect variable expansion, and catch logic errors. 1
Invocation methods
Command line
bash -x ./script.shShebang
#!/usr/bin/env bash -x
# Entire script runs with tracing enabledInline toggle
#!/usr/bin/env bash
# Normal execution...
set -x
# These lines are echoed before execution
set +x
# Back to normal...set -x is frequently used at the top of a script without a closing set +x, which simply traces every line.
PS4: customizing the trace prompt
The PS4 variable controls what prefix appears before each traced line. The default is + . For more detail:
export PS4='+ $(date "+%s.%N") ${LINENO}: ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'This adds timestamps, line numbers, and function names to each trace line — invaluable for long or recursive scripts.
Sources
- The Set Builtin (Bash Reference Manual)
- Bourne Shell Variables (Bash Reference Manual) — Note: PS4 is actually documented in Bash Variables, not Bourne Shell Variables; this page was what the original note cited.
Related: bash-scripting, shell-stabilization