Debugging Scripts with bash -x
When a script behaves differently from what you expected, the hardest part is usually seeing what the shell actually did. Bash's execution trace, called xtrace, shows this directly. With tracing on, Bash prints every command just before running it, after all expansions have been applied: variables replaced by their values, command substitutions run, globs turned into file names. You no longer have to guess what $file held or which branch of an if ran; the trace shows it line by line.
This lesson covers turning the trace on for a whole script or for part of it, reading its output, adding file and line information with PS4, sending the trace to a separate file, and two related options: bash -n for syntax checks and bash -v for printing the source as it is read.
Turning On the Trace for a Whole Script
The simplest way to trace a script is to start it with bash -x:
bash -x greet.sh
Here is greet.sh, run in a folder that contains a.txt, b c.txt and the script itself:
name="Ana Lima"
files=(*.txt)
echo "Hello, $name"
count=$(ls | wc -l)
if (( count > 2 )); then
echo "many files"
fi
+ name='Ana Lima'
+ files=(*.txt)
+ echo 'Hello, Ana Lima'
Hello, Ana Lima
++ ls
++ wc -l
+ count=3
+ (( count > 2 ))
+ echo 'many files'
many files
The lines that start with + are the trace; the other lines are the script's normal output. Several details are worth noticing:
- Values are shown after expansion. The trace prints
echo 'Hello, Ana Lima', notecho "Hello, $name". This is the most useful property of xtrace: you see the arguments the command really received. - Quotes in the trace mark word boundaries. Bash adds single quotes around any word that contains spaces or special characters, so
'Hello, Ana Lima'tells you it was passed as one argument. If a variable had been unquoted in the script, you would see several separate words instead. - Command substitutions are traced one level deeper. The commands inside
$(ls | wc -l)appear with++, before the assignment that uses their result. Each additional level of nested substitution adds another+. - Some compound commands are shown as written. The array assignment
files=(*.txt)and the arithmetic command(( count > 2 ))appear in their source form rather than expanded.
The -x option does not need to be the only one; bash -x script.sh arg1 arg2 passes arguments as usual, and bash -xc 'commands' traces a command string.
The Trace Goes to Standard Error
The trace is written to standard error, not standard output. That keeps it out of pipelines and output files:
bash -x part.sh 2>/dev/null # normal output only, trace discarded
bash -x part.sh 2>trace.log >/dev/null # trace only, saved in a file
The first command shows only what the script prints. The second leaves only the trace, in trace.log. Because the script's own error messages also go to standard error, they land in the same place as the trace when you redirect 2>; the BASH_XTRACEFD section below shows how to separate them.
Tracing Part of a Script with set -x and set +x
Tracing a long script produces a lot of output. Often only one section is suspicious. Inside the script, set -x turns tracing on and set +x turns it off again (lesson 148 covers set in general):
echo "start"
set -x
x=5
y=$((x * 2))
set +x
echo "y=$y"
start
+ x=5
+ y=10
+ set +x
y=10
Only the lines between the two set commands are traced. The set +x line itself appears in the trace, because tracing is still on when Bash prints it. If that line bothers you, run it inside a group whose standard error is discarded:
set -x
x=1
{ set +x; } 2>/dev/null
echo "x=$x"
+ x=1
x=1
The long form set -o xtrace and set +o xtrace does exactly the same as set -x and set +x.
Checking Whether Tracing Is On
The special parameter $- (lesson 43) lists the current single-letter options. When tracing is on, it contains x:
echo "flags: $-"
set -x
[[ $- == *x* ]] && echo "tracing is on"
flags: hB
+ [[ hxB == *x* ]]
+ echo 'tracing is on'
tracing is on
shopt -qo xtrace gives the same answer as an exit status, which reads well in an if.
Tracing Only One Function
A set -x inside a function stays on after the function returns, which is rarely what you want. In Bash 4.4 and later, local - at the start of a function makes any option changes inside it local, so they are undone when the function returns:
calc() {
local -
set -x
local a=$1 b=$2
echo $(( a * b ))
}
echo "before"
calc 6 7
echo "after: flags=$-"
before
+ local a=6 b=7
+ echo 42
42
after: flags=hB
The trace covers only the function body, and $- after the call no longer contains x. Without local -, the same function leaves tracing on, and the line after the call is traced too (+ echo 'after: flags=hxB').
Reading Traces of Loops, Conditions and Functions
The trace follows the flow of the program, so a loop shows its header once per iteration, and an if shows only the branch that ran:
set -x
for f in a.txt "b c.txt"; do
case $f in
*" "*) echo "space in: $f" ;;
esac
done
+ for f in a.txt "b c.txt"
+ case $f in
+ for f in a.txt "b c.txt"
+ case $f in
+ echo 'space in: b c.txt'
space in: b c.txt
The for and case headers are printed as written, but the commands in the body show expanded values. The first iteration printed nothing after case, which tells you that a.txt matched no pattern; the second iteration reached echo.
Function calls appear as ordinary commands with their arguments, followed by the commands in the function body:
set -x
f() { local v=$1; echo "v=$v"; }
f "two words"
+ f 'two words'
+ local 'v=two words'
+ echo 'v=two words'
v=two words
Adding File and Line Numbers with PS4
The + in front of every trace line comes from the variable PS4, whose default value is '+ '. Bash expands PS4 before printing each trace line, and repeats its first character to show the nesting level, which is where ++ comes from.
Because PS4 is expanded each time, it can include variables such as LINENO (the current line number) and BASH_SOURCE (the current file). Set it in single quotes, so the variables are expanded when each trace line is printed, not once when PS4 is assigned:
PS4='+ ${BASH_SOURCE##*/}:${LINENO}: '
set -x
a=1
b=$((a + 1))
greet() { echo "hi $1"; }
greet "$b"
+ ps4.sh:3: a=1
+ ps4.sh:4: b=2
+ ps4.sh:6: greet 2
+ ps4.sh:5: echo 'hi 2'
hi 2
Each line now says where the command lives. The echo inside greet reports line 5, where the function is defined, even though it was called from line 6, which makes it easy to jump to the right place in an editor. ${BASH_SOURCE##*/} removes the folder part of the path (lesson 54), which keeps lines short when a script is run with a full path.
Adding the function name helps in larger scripts. In this version of the script (ps4f.sh), FUNCNAME[0] holds the name of the current function and is empty at the top level, so the :+ expansion (lesson 45) adds the name only when there is one:
PS4='+ ${BASH_SOURCE##*/}:${LINENO}: ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
set -x
greet() { echo "hi $1"; }
greet world
echo done
+ ps4f.sh:4: greet world
+ ps4f.sh:3: greet(): echo 'hi world'
hi world
+ ps4f.sh:5: echo done
done
Lesson 184 explores PS4 and long-running traces in more depth.
Sending the Trace to Its Own File with BASH_XTRACEFD
By default, the trace and the script's own error messages share standard error. Bash 4.1 and later can write the trace to a different file descriptor, named in the variable BASH_XTRACEFD:
exec 5> trace.txt
BASH_XTRACEFD=5
set -x
a=1
echo "a=$a"
echo "warning" >&2
set +x
The terminal shows only the normal output and the real warning:
a=1
warning
and trace.txt holds the trace:
+ a=1
+ echo a=1
+ echo warning
+ set +x
exec 5> trace.txt opens file descriptor 5 for writing (lesson 57 covers >), and setting BASH_XTRACEFD=5 tells Bash to write trace lines there. This is useful when a script normally runs unattended, from cron or a CI job for example, and you want a complete trace kept on disk without changing what users see.
Turning Tracing On from Outside the Script
Editing a script to add set -x and remembering to remove it later is error-prone. A common pattern is to let an environment variable switch tracing on:
#!/usr/bin/env bash
[[ -n ${DEBUG-} ]] && set -x
echo "working"
n=$(( 6 * 7 ))
echo "n=$n"
Normal run, then a run with DEBUG set for that one command:
./dbg.sh
DEBUG=1 ./dbg.sh
working
n=42
+ echo working
working
+ n=42
+ echo n=42
n=42
${DEBUG-} expands to an empty string when the variable is unset, which keeps the line safe under set -u (lesson 120). The name DEBUG is only a convention; some scripts use TRACE or a name specific to the project.
What About #!/bin/bash -x?
Options can also be written on the shebang line:
#!/bin/bash -x
echo "hello"
Run directly as ./she.sh, the script prints + echo hello and then hello. Run as bash she.sh, it prints only hello: the shebang line is just a comment when you name the interpreter yourself (lesson 26). Because the result depends on how the script is started, set -x inside the script, or bash -x on the command line, is more predictable.
Checking Syntax Without Running: bash -n
Some errors are not about behavior at all but about syntax: a missing fi, done or closing quote. Bash reads and runs a script piece by piece, so a script with such an error can run its first commands before the parser reaches the broken part. Consider syn3.sh, whose for loop is never closed:
echo "start"
touch created-by-script.txt
for f in a b; do
echo "$f"
Running it:
start
syn3.sh: line 5: syntax error: unexpected end of file
The status was 2, but echo had already run and touch had already created a file. bash -n reads the whole script and checks its syntax without executing any command:
bash -n syn3.sh; echo "status $?"
syn3.sh: line 5: syntax error: unexpected end of file
status 2
This time no file was created. A clean script produces no output and status 0. bash -n only checks grammar: a misspelled command name, a wrong option or a logic error passes the check, because none of those is a syntax error. The line number points to where Bash noticed the problem, which for a missing done or fi is usually the end of the file, not the line where the block started. ShellCheck (lessons 162 and 190) finds many problems that bash -n cannot.
Printing the Source as It Is Read: bash -v
The -v option (verbose) prints each line of the script as Bash reads it, before any expansion:
# compute
x=3
echo "x is $((x + 1))"
bash -v v.sh
# compute
x=3
echo "x is $((x + 1))"
x is 4
Comments are printed too, because -v shows raw input, not commands. On its own, -v is less informative than -x. Combined as bash -xv, it places each source line next to its expanded trace, which helps when one source line produces several commands:
# compute
x=3
+ x=3
echo "x is $((x + 1))"
+ echo 'x is 4'
x is 4
A Debugging Session from Start to Finish
The following script is meant to warn when a folder holds more than 10 files:
#!/usr/bin/env bash
# report.sh DIR: warn when DIR holds more than 10 files
dir=$1
count=$(ls "$dir" | wc -l)
if [ $count > 10 ]; then
echo "warning: $dir holds $count files"
else
echo "$dir is fine ($count files)"
fi
The folder proj holds three files, yet the script warns:
bash report.sh proj
warning: proj holds 3 files
The count printed in the message is correct, so the problem is in the condition. Running the script with the trace shows what the test command really received:
bash -x report.sh proj
+ dir=proj
++ ls proj
++ wc -l
+ count=3
+ '[' 3 ']'
+ echo 'warning: proj holds 3 files'
warning: proj holds 3 files
The test ran as [ 3 ], with no operator and no 10. Inside [ ], > 10 is not a comparison: it is an output redirection, so the shell sent the (empty) output of [ to a file named 10, and the test that remained, [ 3 ], checks only whether the string 3 is non-empty, which is always true. A listing of the folder confirms that a file named 10 appeared. The fix is the integer operator -gt (lesson 73), with the variable quoted:
if [ "$count" -gt 10 ]; then
The trace of the corrected script:
+ dir=proj
++ ls proj
++ wc -l
+ count=3
+ '[' 3 -gt 10 ']'
+ echo 'proj is fine (3 files)'
proj is fine (3 files)
Now the test shows all four words, and the else branch runs. This is the typical way xtrace helps: the source looked reasonable, but the expanded command made the mistake obvious.
Things the Trace Can Reveal Unintentionally
The trace prints values exactly, which includes passwords, tokens and other secrets that pass through variables or command arguments. A traced curl -H "Authorization: Bearer $token" writes the token to standard error, and from there into terminals, CI logs and saved trace files. Turn tracing off around such commands with { set +x; } 2>/dev/null and turn it back on afterwards, or avoid enabling tracing in scripts that handle credentials. Lesson 158 covers secrets in scripts in detail.