Debugging Scripts with bash -x

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 126 of 205

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', not echo "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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Debugging Scripts with bash -x and get answers drawn from it.

Signed-in readers only.