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 output
You 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.sh
Create script#! /bin/sh
set -x
Turn on tracingecho 1st echo
Do somethingset +x
Turn off tracingecho 2nd echo
Do something else^D
Terminate with end-of-file $chmod +x trace1.sh
Make program executable $./trace1.sh
Run 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.
Get Classic Shell Scripting now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.