The Analogy: The Wind-Tunnel Smoke Trace
In an aerodynamics laboratory a scale model sits bolted to a sting in the working section of a wind tunnel, and the fan drives a steady stream of air over it. The trouble is that air is invisible. The engineer can read a force balance and see that the model produces too much drag, but the numbers alone never say why: where the flow stays attached, where it tumbles into turbulence, where a vortex peels off an edge. The behaviour that matters is happening in plain sight and cannot be seen at all.
So the lab keeps a smoke rake: a comb of fine tubes mounted upstream that bleeds thin ribbons of white smoke into the airstream. Each ribbon is a streamline made visible. Where the flow is smooth the ribbons run straight and parallel; where it separates they burst into curls; where two currents meet they braid together. The engineer can aim the rake at just the part of the model under study -- the leading edge, the flap hinge, the wake behind the tail -- and read the story of the flow directly off the shape of the smoke.
Good tunnel technique is mostly about restraint. You do not fill the whole tunnel with smoke; you feed it only into the band of air passing over the feature you care about, and you switch it off the moment you have seen what you came to see. The smoke is watched through a glass viewing window under a bright light, often photographed frame by frame, so that the record can be studied later without the operator having to stand in the fog. The rake has a valve precisely so the smoke can be turned on for one region and one moment and then shut off again.
The catch is that the smoke is never entirely a passive observer. The tubes themselves sit in the flow and disturb it slightly, so a delicate feature can be nudged by the very thing sent to reveal it. Worse, an operator who cranks the smoke up too high fills the whole section with a uniform white haze: now nothing is visible, because everything is. The instrument that turns invisible flow into a legible picture will, if used without discipline, either perturb the thing it measures or drown the one detail that mattered in an undifferentiated cloud.
Syntax or Core Structure
The shell's smoke rake is set -x, also called xtrace. Once it is on, the shell prints every command to standard error just before running it, after all expansions have been applied, each line prefixed by the trace prompt PS4 (default + ). The commands still run exactly as before; the trace is an extra narration alongside the normal output.
#!/usr/bin/env bash
set -x
name="ada"
echo "hello $name"
Output:
+ name=ada
+ echo 'hello ada'
hello ada
The first two lines, beginning with + , are the trace on standard error; the last line, hello ada, is the program's real output on standard out. Notice the trace shows echo 'hello ada' with the variable already expanded and re-quoted -- you are seeing what the shell actually ran, not what you typed. This is the whole point: the trace reveals the commands after the shell has done its expansions, which is exactly where most bugs hide.
You rarely want the smoke on for the entire script. Turn it on with set -x and off again with set +x to trace just the stretch you are studying:
#!/usr/bin/env bash
set -x
step="one"
set +x
echo "quiet: $step"
Output:
+ step=one
+ set +x
quiet: one
The assignment and the set +x command itself are traced; everything after set +x runs silently. Bracketing xtrace around a single suspect region keeps the trace short and readable, the way an operator feeds smoke into only the band of air over the feature under study.
Technical Depth: Reading What the Trace Is Telling You
Expansion and nesting depth
The trace is drawn after expansion, so command substitutions, arithmetic, globs, and variable references all appear in their final form. When a command contains a substitution, the shell runs that inner command first, and the trace marks the extra level of nesting by repeating the first character of PS4. A single + is the top level; ++ is one level down, inside a command substitution or subshell.
#!/usr/bin/env bash
set -x
echo "count: $(echo hi | wc -w)"
Output:
++ echo hi
++ wc -w
+ echo 'count: 1'
count: 1
Read it from the inside out. The two ++ lines are the pipeline inside the substitution running first; then the outer echo runs at the top + level, and by now the substitution has collapsed to the string count: 1, which is why the trace shows echo 'count: 1' rather than the original source. The depth markers let you see at a glance how far inside a subshell any given command is executing, without counting parentheses by hand.
PS4: labelling every traced line
The default + prefix tells you the nesting depth but nothing about where in the script you are. Redefine PS4 to include ${LINENO} and every trace line carries its own line number, which turns a wall of trace into a map you can follow against the source.
#!/usr/bin/env bash
export PS4='+ ${LINENO}: '
set -x
a=1
b=2
echo "$((a + b))"
Output:
+ 4: a=1
+ 5: b=2
+ 6: echo 3
3
Each traced line now names the line of the script that produced it, and the arithmetic has already collapsed: line 6 traces as echo 3, not echo "$((a + b))". Because PS4 is expanded fresh for every traced command, you can put other information in it too -- ${BASH_SOURCE}, ${FUNCNAME[0]} -- though anything you embed is evaluated on every single line, so keep it cheap. The flags that shape this narration are worth knowing as a set:
| Flag | Long name | What it prints |
|---|---|---|
set -x | xtrace | each command after expansion, to stderr, prefixed by PS4 |
set -v | verbose | each input line as read, before any expansion |
set -n | noexec | nothing runs; the script is parsed for syntax only |
set +x | (off) | turns xtrace back off |
Verbose is not xtrace
It is easy to confuse set -v with set -x. Verbose echoes each line of the script exactly as it was read, before the shell touches it; xtrace echoes each command after expansion, just before it runs. The difference shows up the moment a variable is involved.
#!/usr/bin/env bash
set -v
x="a b"
echo "$x"
Output:
x="a b"
echo "$x"
a b
With verbose, the trace lines are the literal source -- echo "$x" still shows the unexpanded variable -- and the program's real output, a b, follows. Use verbose when you want to see the script as written; use xtrace when you want to see what it actually did after expansion. Most debugging wants xtrace.
Keeping the trace out of your output
By default the trace lands on standard error, mixed into the terminal alongside the program's real output. To study it later, or to keep it from polluting output that another program consumes, point it at its own file descriptor with BASH_XTRACEFD.
#!/usr/bin/env bash
exec 3>trace.log
export BASH_XTRACEFD=3
set -x
echo "result"
Output:
result
The only thing on the terminal is result; the trace has been routed to the file instead. trace.log now contains:
+ echo result
This is the glass viewing window of the wind tunnel: the smoke is captured where you can study it, without fogging the room the program is running in.
Real World Example: A Config Auditor You Can Trace on Demand
A script that reads other people's configuration files fails in the field far more often than it does on your desk, and the failures are exactly the kind xtrace was made for: a key that is present but misspelled, a grep pattern that does not match what you assumed, a file with different line endings. The script below checks that a config declares the required keys, and it carries its own smoke rake: set TRACE=1 in the environment and it routes a fully labelled xtrace to a file, without changing a line of its own logic.
#!/usr/bin/env bash
# require-keys.sh -- report which required config keys are missing, tracing on demand
set -euo pipefail
if [ "${TRACE:-0}" = "1" ]; then
exec 3>>require-keys.trace
export BASH_XTRACEFD=3
export PS4='+ ${LINENO}: '
set -x
fi
config="${1:?usage: require-keys.sh CONFIG}"
missing=0
for key in host port user; do
if ! grep -q "^${key}=" "$config"; then
echo "missing: $key"
missing=1
fi
done
if [ "$missing" -eq 0 ]; then
echo "all required keys present"
fi
exit "$missing"
Given a valid config with all three keys:
host=db.internal
port=5432
user=app
running the auditor reports success and exits zero:
bash require-keys.sh good.conf
Output:
all required keys present
Drop the port line, and it names exactly what is missing and exits non-zero:
host=db.internal
user=app
bash require-keys.sh bad.conf
Output:
missing: port
Now turn the smoke on. Set TRACE=1 and the same run writes a labelled trace to a file, while the terminal still shows only the real result:
TRACE=1 bash require-keys.sh good.conf
Output:
all required keys present
The file require-keys.trace now holds the story of the run, one line per command with its line number:
+ 12: config=good.conf
+ 13: missing=0
+ 15: for key in host port user
+ 16: grep -q '^host=' good.conf
+ 15: for key in host port user
+ 16: grep -q '^port=' good.conf
+ 15: for key in host port user
+ 16: grep -q '^user=' good.conf
+ 22: '[' 0 -eq 0 ']'
+ 23: echo 'all required keys present'
+ 26: exit 0
On a normal run the auditor loops over the three required keys, greps for each one anchored to the start of a line, and prints missing: for any it cannot find, tracking a missing flag it finally returns as the exit status. A caller can therefore branch on the exit code alone, and a human gets a plain-language list of what to fix. None of this changes when tracing is enabled; the TRACE block only redirects and decorates the narration.
The trace file is the payoff. Every line is stamped with the source line number from PS4, so + 16: grep -q '^host=' good.conf tells you both what ran and where it lives in the script. You can see the loop revisit line 15 three times, watch the [ test builtin traced as '[' 0 -eq 0 ']' with its arguments already substituted, and confirm the script left through line 26 with status 0. When a config fails in a way you did not predict, this file is the difference between guessing and reading the answer.
The script has honest limits worth stating. The trace file is opened with >>, so repeated traced runs append to require-keys.trace forever rather than starting fresh -- yesterday's trace sits above today's and quietly misleads unless you truncate the file yourself. The key check is shape-blind in two directions: ^${key}= reports port = 5432 (with spaces around the equals) as missing, and accepts port= with an empty value as present, because it tests for a prefix, not for a real value. And the trace path is a fixed relative name, so the auditor assumes the current directory is writable and unshared. Each of these is fixable, but each is a real trap that only a careful reading -- aided, fittingly, by xtrace -- would catch.
Common Mistakes
- Tracing the whole script instead of the suspect region. Turning
set -xon at the top of a long script buries the three lines that matter under hundreds that do not -- the wind tunnel filled with smoke. Bracket the trace withset -xandset +xaround the stretch you actually doubt.
- Expecting the trace on standard output. xtrace writes to standard error, so
script.sh > out.txtcaptures the program's output but not the trace, and a downstream pipe never sees it. Redirect deliberately with2>trace.txt,2>&1, orBASH_XTRACEFDwhen you want to keep or move the trace.
- Setting PS4 without exporting it. A bare
PS4='+ ${LINENO}: 'shapes the current shell's trace, but a child shell started withbash -x child.shgets the default+becausePS4was never exported. Useexport PS4=...when the trace of sub-scripts must match.
- Putting an expensive or side-effecting command in PS4.
PS4is expanded before every single traced line, so a command substitution inside it runs hundreds of times and can slow the script or, worse, change its state -- the smoke rake disturbing the very flow it reveals. KeepPS4to cheap variables like${LINENO}.
- Confusing set -v with set -x. Verbose shows the source line as written; xtrace shows the command after expansion. Reaching for
set -vto see what a variable expanded to shows you the unexpanded$varinstead, and you conclude nothing. Match the flag to the question.
- Trusting set -n to find logic errors.
set -nparses without executing, so it catches an unbalanced quote or a missingfi, but never a wrong comparison or a bad path -- those only appear at run time. It is a syntax check, not a correctness check, and running it in an interactive shell locks the session.
- Letting secrets leak into the trace. Because xtrace prints commands after expansion, a line like
curl -H "Authorization: $token"writes the real token into the trace and any file it is routed to. Disable tracing around sensitive commands, or redact, before the log is shared or committed.
- Leaving debug output enabled in shipped code. A stray
set -xor a#!/usr/bin/env bash -xshebang left in after debugging floods production logs and can expose internals. Treat trace flags as temporary and strip them, or gate them behind an explicit variable like theTRACEswitch above.
- Copying re-quoted trace lines back as source. The trace shows the shell's own re-quoting, such as
echo 'hello ada', which is equivalent to what you wrote but not identical to it. Pasting trace lines into a script as if they were the original can subtly change quoting and word-splitting.
Best Practices
- Bracket xtrace to the smallest region that reproduces the problem. Turn
set -xon just before the suspect code andset +xjust after, so the trace is short enough to read line by line rather than scrolling past in a blur.
- Put
${LINENO}in PS4 so every trace line is navigable. Setexport PS4='+ ${LINENO}: 'and each traced command names its own source line, turning the trace into a map you can follow straight back into the script.
- Route the trace to its own file descriptor. Use
BASH_XTRACEFDwith a dedicatedexec 3>trace.logso the trace never mingles with the program's real output and can be studied or diffed after the run.
- Gate tracing behind an environment switch, not an edit. Wrap the trace setup in
if [ "${TRACE:-0}" = "1" ]so operators enable it withTRACE=1in the field without touching the code, and normal runs stay silent.
- Prefer xtrace over scattered echo statements. A trace is generated from the code itself, so it cannot drift out of date the way hand-placed
echolines do, and it needs no cleanup beyond turning the flag off.
- Combine tracing with
set -euo pipefail. With strict mode on, the trace stops at the first genuine failure instead of scrolling on past it, so the last traced line is usually the command that broke.
- Keep secrets out of the trace. Disable xtrace around commands that handle tokens or passwords, or redact them, because xtrace prints fully expanded arguments into whatever file the trace is routed to.
- Check syntax before you trace behaviour. Run
bash -n script.shor a static analyser first to catch parse errors, then use xtrace to study what the running script actually does; the two tools answer different questions.
Practice Exercises
- Bracketed trace. Write a script that does three assignments and one
echo, but enableset -xonly around the middle assignment andset +ximmediately after. Run it and confirm the trace contains exactly one+line, proving the smoke was confined to the region you chose.
- Line-numbered PS4. Take any short script, add
export PS4='+ ${LINENO}: 'beforeset -x, and run it. Verify that each traced line is prefixed by the correct source line number, and explain why an arithmetic expression traces in its already-evaluated form.
- Trace behind a switch, routed to a file. Add a
TRACEgate to a script so thatTRACE=1opens a file descriptor withexec, pointsBASH_XTRACEFDat it, and enablesset -x, while a normal run prints nothing extra. Show that the program's output is identical with and without the switch.
- Find the bug with xtrace. Write a script with a deliberate quoting bug, such as a variable that word-splits when it should not, then run it under
bash -xand use the trace to pinpoint the exact command where the expanded value differs from what you intended. Describe how the trace revealed it.