Bash Tracing with Set X
Tracing with set -x is a debug mode that prints each command before it runs. The trace shows the expanded command, so a wrong value is easy to spot.
Tracing shows each command as it runs
Tracing starts after set -x and stops at set +x. The trace line shows the expanded echo command.
name="ada"
set -x
echo "hello $name"
set +x
echo "done"PS4 gives every trace line a fixed prefix
PS4 is set to a fixed word before tracing starts. Every trace line then starts with that word.
PS4="TRACE: "
set -x
city="Oslo"
echo "city is $city"
set +x
echo "after"Tracing shows arithmetic already worked out
The trace shows total=5, not the sum that produced it. The printed line then confirms the same value.
total=0
set -x
total=$((total + 5))
echo "total is $total"
set +x
echo "total done"Example
PS4="TRACE: "
name="Sam"
set -x
greeting="Hello $name"
echo "$greeting"
set +x
echo "greeting done"Key points
- set -x: a switch that turns command tracing on.
- set +x: the switch that turns tracing off again.
- Trace line: the expanded command, shown before it runs.
- stderr: the stream that carries trace lines, not stdout.
- PS4: the prefix printed at the start of each trace line.
- Scope: keep tracing on for one section only, then switch it off.
In this example, PS4 sets a fixed trace prefix before tracing starts. The set -x line turns tracing on for the greeting section only. The trace shows the greeting assignment already expanded. The set +x line ends tracing, and the last echo prints without a trace line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does set -x send its trace lines?