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.sh

Shebang

#!/usr/bin/env bash -x
 
# Entire script runs with tracing enabled

Inline 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

Related: bash-scripting, shell-stabilization

Footnotes

  1. The Set Builtin (Bash Reference Manual)