Debugging Your Script

If a script doesn’t do what you expect, or if a variable doesn’t seem to have the value you think it should, you can do a couple things to debug the problem. The easiest is to use the -x option to the Bourne shell. You can do this by modifying the first line of your script to look like this:

#!/bin/sh -x

Or, you can run the shell directly on your script with the -x option, like this:

sh -x scriptname

Debug Info Goes to Standard Error

The shell -x option outputs the commands being executed to standard error. To page this output, do this:

sh -x scriptname >&2 | pg

To save it in a file, enter this:

sh -x scriptname >&2 |tee filename

Both methods accomplish the same thing; the shell is instructed to print each line in the ...

Get Practical UNIX 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.