Simple Execution Tracing
Because program development is a human activity, there
will be times when your script just doesn't do what you want it to do.
One way to get some idea of what your program is doing is to turn on
execution tracing. This causes the shell to print
out each command as it's executed, preceded by "+ "—that is, a plus
sign followed by a space. (You can change what gets printed by assigning
a new value to the PS4 shell
variable.) For example:
$ sh -x nusers
Run with tracing on
+ who Traced commands
+ wc -l
7 Actual outputYou can turn execution tracing on within a script by using the
command set -x, and turn it
off again with set +x. This is more
useful in fancier scripts, but here's a simple program to
demonstrate:
$cat > trace1.shCreate script#! /bin/shset -xTurn on tracingecho 1st echoDo somethingset +xTurn off tracingecho 2nd echoDo something else^DTerminate with end-of-file $chmod +x trace1.shMake program executable $./trace1.shRun it + echo 1st echo First traced line 1st echo Output from command + set +x Next traced line 2nd echo Output from next command
When run, the set -x is not
traced, since tracing isn't turned on until after that command
completes. Similarly, the set +x is
traced, since tracing isn't turned off until after it completes. The
final echo isn't traced, since
tracing is turned off at that point.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access