Using set -x and PS4 for Debug Traces
set -x turns on Bash's execution trace, also called xtrace. While it is on, Bash prints every command to standard error just before running it, after all expansions have been performed: variables replaced by their values, command substitutions by their output, wildcards by file names. The trace shows what the script actually does, not what its source code seems to say, which makes it the most direct way to understand a misbehaving script.
The prompt variable PS4 controls the text that starts every trace line. By default it is just + , but it can include the file name, line number, function name, or a precise timestamp. With a well-chosen PS4, a trace becomes a detailed log of the script's execution, and with timestamps, even a simple profiler. This lesson covers how to turn tracing on and off precisely, how to read a trace, how to design PS4, how to send traces to a file, and how to avoid the traps of tracing, such as leaking passwords.
Turning Tracing On and Off
There are several ways to enable the trace, each suited to a different situation:
| Method | Effect |
|---|---|
bash -x script.sh | traces the whole run of one script, without editing it |
set -x / set +x in the script | traces only the commands between the two |
set -o xtrace / set +o xtrace | the long names of the same two options |
#!/bin/bash -x in the first line | traces every run of the script |
The shebang variant has a portability catch. #!/usr/bin/env bash is the recommended first line (lesson 26), but on Linux, the kernel passes everything after the interpreter path to it as one argument, so env receives bash -x as the name of the program to start:
$ cat shebang.sh
#!/usr/bin/env bash -x
echo hi
$ ./shebang.sh
/usr/bin/env: 'bash -x': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
[status 127]
GNU env offers -S, which splits the string, so #!/usr/bin/env -S bash -x works on current Linux distributions. In practice, it is simpler to put set -x on the second line, or better, to make tracing switchable, as shown later in this lesson.
Reading a Trace
Consider this small script:
#!/usr/bin/env bash
greet() {
local name=$1
echo "Hello, $name"
}
file='monthly report.csv'
count=$(ls | wc -l)
if [[ $count -ge 1 ]]; then
greet "$USER"
fi
(( total = count * 2 ))
printf '%s\n' "$file" > /dev/null
Running it with bash -x produces this trace, mixed with the script's normal output:
+ file='monthly report.csv'
++ ls
++ wc -l
+ count=1
+ [[ 1 -ge 1 ]]
+ greet dev
+ local name=dev
+ echo 'Hello, dev'
Hello, dev
+ (( total = count * 2 ))
+ printf '%s\n' 'monthly report.csv'
Several details of the trace format are worth knowing:
- Values are shown after expansion.
[[ $count -ge 1 ]]appears as[[ 1 -ge 1 ]]andgreet "$USER"asgreet dev, so you see the values the commands actually received. - Quotes in the trace show argument boundaries. Bash quotes each word that would otherwise be ambiguous.
'monthly report.csv'is one argument containing a space. If the trace showedprintf '%s\n' monthly report.csv, the file name would have been split into two arguments. The quotes are added by the trace for clarity; they are not part of the values. - Redirections are not shown. The
> /dev/nullof the last command does not appear in the trace. Where output goes must be checked in the source. - Structure is not shown, only commands.
if,thenandfido not appear; only the commands they contain, such as the condition[[ ... ]]. Arithmetic commands appear with their expression, but variable names inside(( ))are not replaced by values. - The number of
+signs shows the nesting level. The first character ofPS4is repeated once for each level of indirection.lsandwc -lran inside the command substitution$(ls | wc -l), so they are marked++; deeper nesting adds more signs:
+++ 2: date +%Y
++ 1: echo 2026
+ 0: x=2026
This trace comes from x=$(echo $(date +%Y)) with PS4='+ $BASH_SUBSHELL: ': the inner date runs two levels deep, echo one level, and the assignment in the script itself.
- Pipeline commands may appear in any order. All commands of a pipeline start at the same time, so their trace lines can appear in a different order from one run to the next.
Designing PS4
The default + marker tells you nothing about where a command comes from. In a script with functions, loops and several files, a trace line such as + rm -rf -- /tmp/build raises the question: which line ran this? PS4 answers it. Like the other prompt variables, PS4 is expanded every time it is displayed, so it can contain variables that change from line to line:
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
${BASH_SOURCE##*/}is the name of the file that contains the current command, with the directory removed by the##*/expansion (lesson 152). This matters when a script loads other files withsource.${LINENO}is the current line number in that file.${FUNCNAME[0]:-main}is the current function's name. At the top level of a script,FUNCNAMEis empty, and:-mainsubstitutesmain.
The value must be in single quotes. Single quotes store the text ${LINENO} itself in PS4, and Bash expands it fresh for every trace line. With double quotes, the variables would be expanded once, when PS4 is assigned, and every trace line would show the same line number:
$ bash -c 'PS4="+ line $LINENO: "; set -x; a=1
b=2'
+ line 1: a=1
+ line 1: b=2
With the improved PS4, the trace of a script with a function locates every command:
#!/usr/bin/env bash
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
set -x
greet() {
local name=$1
echo "Hello, $name"
}
count=$(ls | wc -l)
greet "$USER"
++ ps4.sh:8:main: ls
++ ps4.sh:8:main: wc -l
+ ps4.sh:8:main: count=2
+ ps4.sh:9:main: greet dev
+ ps4.sh:5:greet: local name=dev
+ ps4.sh:6:greet: echo 'Hello, dev'
Hello, dev
Keep the first character of PS4 a + or another single character: Bash repeats only that character to show nesting, so a value starting with a space or a long word makes the levels hard to see.
PS4 can be set in the script, as above, or before running bash -x at the prompt with export PS4='...'. One restriction applies: since Bash 4.4, a shell started as root ignores a PS4 it inherits from the environment, because the expansion of PS4 can run arbitrary commands and an inherited value could be used to attack root scripts. The same command shows the difference:
# as root
$ PS4='+ [env PS4] ' bash -xc 'a=1'
+ a=1
# as an ordinary user
$ PS4='+ [env PS4] ' bash -xc 'a=1'
+ [env PS4] a=1
For scripts that run as root, such as many system administration scripts, set PS4 inside the script.
Tracing Only What Matters
Tracing a whole script quickly produces thousands of lines. Usually only one section or one function is of interest.
Hiding the set +x Line
set +x is itself traced, because tracing is still on when it runs. That one extra line is harmless, but in clean traces or in output shown to users it can be suppressed by running set +x in a group whose standard error is discarded:
#!/usr/bin/env bash
set -x
step=1
set +x
echo "tracing is off"
set -x
step=2
{ set +x; } 2> /dev/null
echo "tracing is off, and the set +x line is hidden"
+ step=1
+ set +x
tracing is off
+ step=2
tracing is off, and the set +x line is hidden
The braces { ...; } group the command without creating a subshell, so set +x still affects the script. The redirection 2> /dev/null applies to the whole group, including the trace line of set +x.
Tracing a Single Function with local -
Turning tracing on inside a function and off at its end breaks as soon as the function has several return statements, or exits early because of an error. Since Bash 4.4, local - solves this: it makes the shell options local to the function, so any option changed with set inside the function is restored automatically when the function returns:
#!/usr/bin/env bash
trace_this() {
local - # options changed in this function are restored when it returns
set -x
local sum=$(( $1 + $2 ))
echo "sum=$sum"
}
echo "before"
trace_this 2 3
echo "after: tracing is off again"
before
+ local sum=5
+ echo sum=5
sum=5
after: tracing is off again
A Switch Instead of Editing the Script
Adding and removing set -x lines by hand is error-prone; it is easy to commit a script with tracing still on. A better approach is a switch controlled by an environment variable, placed near the top of the script:
[[ -n ${TRACE:-} ]] && set -x
The script runs quietly by default, and TRACE=1 ./script.sh produces a full trace without any change to the file. The complete example at the end of this lesson extends this switch.
Tracing Child Scripts
bash -x parent.sh traces only parent.sh. Scripts it starts are new Bash processes, which start with default options, so their commands are not traced:
$ bash -x parent.sh
+ echo 'parent running'
parent running
+ ./child.sh
child running
Bash reads its initial options from the SHELLOPTS environment variable if it exists. Setting it to xtrace for one command traces the whole tree of Bash scripts started from it:
$ env SHELLOPTS=xtrace ./parent.sh
+ echo 'parent running'
parent running
+ ./child.sh
+ echo 'child running'
child running
Sending the Trace to a File
The trace is written to standard error, where it mixes with the script's own error messages and, in a terminal, with its normal output. For long traces, a separate file is much easier to search. The variable BASH_XTRACEFD (Bash 4.1 and later) names a file descriptor to which the trace is written instead:
#!/usr/bin/env bash
exec {trace_fd}> trace.log # open trace.log; Bash picks a free descriptor number
BASH_XTRACEFD=$trace_fd
set -x
for n in 1 2; do
echo "visible output $n"
done
echo "an error message" >&2
$ bash fd.sh
visible output 1
visible output 2
an error message
$ cat trace.log
+ for n in 1 2
+ echo 'visible output 1'
+ for n in 1 2
+ echo 'visible output 2'
+ echo 'an error message'
exec {trace_fd}> trace.log opens the file for writing and stores the number of a free file descriptor in trace_fd (Bash 4.1 and later), so the script does not have to pick a number that might already be in use. The script's output and error messages stay on the terminal, unchanged, while the complete trace lands in the file. This is especially useful for scripts whose standard error is shown to users or parsed by another program.
Timestamps: A Trace That Measures Time
Bash 5.0 introduced the variable EPOCHREALTIME, which contains the current time in seconds since 1970 with microsecond precision, such as 1796104596.114481. Placed in PS4, it stamps every trace line with the moment the command started:
PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
The difference between two consecutive timestamps is the time the first command took, including any child processes it waited for. A trace with timestamps therefore contains all the data needed to find out where a slow script spends its time, without changing a single line of the script's logic. In some locales, EPOCHREALTIME is written with a decimal comma instead of a point; a program that reads the timestamps should accept both.
Secrets in Traces
Because the trace shows every value after expansion, it also shows passwords, tokens and keys:
#!/usr/bin/env bash
set -x
DB_PASSWORD=$(cat db-password.txt)
mysql_cmd() { echo "connecting as shop"; }
mysql_cmd --user=shop --password="$DB_PASSWORD"
++ cat db-password.txt
+ DB_PASSWORD='S3cr3t!pw'
+ mysql_cmd --user=shop '--password=S3cr3t!pw'
+ echo 'connecting as shop'
connecting as shop
The password appears twice. Traces end up in CI logs, bug reports and chat messages, so a script that handles secrets must turn tracing off around them, for example with { set +x; } 2> /dev/null before the sensitive commands and set -x after them, or by moving them into a function that starts with local - and set +x. Lesson 158 covers secret handling in general; for traces, the rule is simple: never share a trace of a script that touches credentials without checking it first.
A Complete Example: A Script with Built-In Tracing and a Trace Profiler
build-site.sh renders the Markdown pages of a small website into HTML and compresses the results. It contains a reusable tracing block with two modes: TRACE=1 traces to standard error with file, line and function names, and TRACE=FILE writes a timestamped trace to a file for profiling. The sleep commands stand in for slow tools such as a template engine and an image optimizer.
#!/usr/bin/env bash
#
# build-site.sh - render the Markdown pages in site/pages into HTML in site/public
#
# Tracing: TRACE=1 ./build-site.sh trace to standard error
# TRACE=trace.log ./build-site.sh trace to a file, with timestamps for profiling
set -euo pipefail
if [[ -n ${TRACE:-} ]]; then
if [[ $TRACE == 1 ]]; then
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
else
PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
exec {trace_fd}>> "$TRACE"
BASH_XTRACEFD=$trace_fd
fi
set -x
fi
render_page() { # render_page SRC DEST: a tiny Markdown-to-HTML step
local title
title=$(head -n 1 "$1" | sed 's/^# //')
sleep 0.05 # stands in for a slow template engine
{
printf '<h1>%s</h1>\n' "$title"
tail -n +3 "$1" | sed 's/.*/<p>&<\/p>/'
} > "$2"
}
compress_assets() {
local f
for f in site/public/*.html; do
gzip -9 -k -f -- "$f"
done
sleep 0.3 # stands in for image optimization
}
mkdir -p site/public
for src in site/pages/*.md; do
name=${src##*/}
render_page "$src" "site/public/${name%.md}.html"
done
compress_assets
echo "built $(ls site/public/*.html | wc -l) pages"
The trace file is opened with >>, so several runs can be collected in one file. PS4 is set before set -x, so the first traced command already uses the detailed format.
The second script, trace-profile.sh, reads a timestamped trace and shows which source lines took the most time:
#!/usr/bin/env bash
#
# trace-profile.sh - show where a script spent its time, from a timestamped xtrace log
#
# Usage: trace-profile.sh TRACEFILE [N]
# The trace must have been written with
# PS4='+ ${EPOCHREALTIME} ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
# Each trace line is charged with the time until the next trace line.
set -euo pipefail
trace=${1:?usage: trace-profile.sh TRACEFILE [N]}
top=${2:-5}
awk '
$1 ~ /^\++$/ && $2 ~ /^[0-9]+[.,][0-9]+$/ { # only trace lines: "+..." then a timestamp
t = $2; sub(",", ".", t); t += 0 # some locales write a decimal comma
if (n++) { spent[where] += t - prev; count[where]++ }
prev = t; first = (n == 1 ? t : first)
where = $3; sub(/:$/, "", where) # "build-site.sh:24:render_page"
}
END {
printf "total %.3f s over %d traced commands\n", prev - first, n
for (w in spent) printf "%8.3f s %5.1f%% %5d %s\n", spent[w], 100 * spent[w] / (prev - first), count[w], w
}
' "$trace" | { IFS= read -r header; echo "$header"; sort -rn | awk -v n="$top" 'NR <= n'; }
How It Works
- Selecting trace lines. A trace file can contain other text, for example output of commands that write to the same file descriptor. The condition accepts only lines whose first field consists of
+signs and whose second field looks like a timestamp. - Charging time. For each trace line, the time until the next trace line is added to the location of the current line,
spent[where]. The location fieldbuild-site.sh:24:render_page:identifies the file, line and function; the trailing colon is removed.countrecords how often each line ran. The very last traced command gets no time, because no later timestamp exists; for a profile, that small inaccuracy does not matter. - Total and percentages.
firstremembers the first timestamp andprevends up as the last one, soprev - firstis the traced run time. - Keeping the header on top. The awk output starts with a summary line, followed by unsorted rows. The command group
{ ...; }reads the first line withread, prints it, and then sorts only the remaining lines. As in lesson 181,awk 'NR <= n'replacesheadso thatsortis never killed bySIGPIPEunderpipefail.
Running the Complete Example
Without tracing, the build is silent apart from its result:
$ ./build-site.sh
built 5 pages
With TRACE=1, every command appears with its location. The beginning of the trace shows the loop processing the first page:
$ TRACE=1 ./build-site.sh
+ build-site.sh:39:main: mkdir -p site/public
+ build-site.sh:40:main: for src in site/pages/*.md
+ build-site.sh:41:main: name=about.md
+ build-site.sh:42:main: render_page site/pages/about.md site/public/about.html
+ build-site.sh:22:render_page: local title
++ build-site.sh:23:render_page: head -n 1 site/pages/about.md
++ build-site.sh:23:render_page: sed 's/^# //'
+ build-site.sh:23:render_page: title=about
+ build-site.sh:24:render_page: sleep 0.05
+ build-site.sh:26:render_page: printf '<h1>%s</h1>\n' about
+ build-site.sh:27:render_page: sed 's/.*/<p>&<\/p>/'
+ build-site.sh:27:render_page: tail -n +3 site/pages/about.md
+ build-site.sh:40:main: for src in site/pages/*.md
+ build-site.sh:41:main: name=blog.md
...
On line 27, sed was traced before tail, although tail comes first in the pipeline: both started at the same moment, and the order of their trace lines is a matter of timing.
With TRACE=trace.log, the trace goes to the file with timestamps, and the terminal shows only the normal output:
$ TRACE=trace.log ./build-site.sh
built 5 pages
$ wc -l trace.log
72 trace.log
$ head -n 4 trace.log
+ 1796104596.114481 build-site.sh:39:main: mkdir -p site/public
+ 1796104596.116844 build-site.sh:40:main: for src in site/pages/*.md
+ 1796104596.116890 build-site.sh:41:main: name=about.md
+ 1796104596.116916 build-site.sh:42:main: render_page site/pages/about.md site/public/about.html
The profiler turns the 72 trace lines into a ranking:
$ ./trace-profile.sh trace.log
total 0.605 s over 72 traced commands
0.302 s 50.0% 1 build-site.sh:36:compress_assets
0.260 s 42.9% 5 build-site.sh:24:render_page
0.012 s 2.0% 15 build-site.sh:23:render_page
0.012 s 2.0% 10 build-site.sh:27:render_page
0.007 s 1.2% 5 build-site.sh:34:compress_assets
The ranking points straight at the two sleep lines that stand in for the slow tools: line 36 ran once and took half of the total time, and line 24 ran five times, about 0.05 seconds each. Line 23 ran 15 times, once for each of the three trace lines of its command substitution per page, and is cheap. In a real script, this is exactly the information needed before optimizing (lesson 191 covers Bash performance): it shows which lines are worth improving and which are not.
The examples in this lesson were run with Bash 5.2 on Ubuntu 24.04. local - requires Bash 4.4, BASH_XTRACEFD and exec {var}> Bash 4.1, and EPOCHREALTIME Bash 5.0; the Bash 3.2 that macOS installs by default supports none of them, but a current Bash from Homebrew does.