DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

What to do if your shell script fails

In the meantime, if your shell scripts fail, a useful technique for finding out what is going wrong is to use the -x flag. You can set it when you start ksh by running the shell with the command ksh -x; or you can set it from within the Korn shell by issuing the following command:

set -o xtrace

The Bourne shell's equivalent is as follows:

set -x

The xtrace option causes the Korn shell to list each command after it has been expanded, but before it has been executed. This enables you to catch any errors due to alias substitution, wildcard expansion, or quote stripping.

(The set -o command can be used to reset the Korn shell's startup options from within a running shell; type set -o for a listing of the current option states, then use set -o option to switch option on, or set +o option to switch option off.) The set - command will also turn off the xtrace facility.

Another useful technique is to use print as frequently as possible, to let you know what your script thinks it is meant to be doing. Print the contents of variables before and after you change them, along with a message to explain what kind of operation you are carrying out. Better still, make print send this output to a log file. The file provides you with a permanent record of what happened during a test run of the script.

An important rule to bear in mind if your script fails is not to change more than one thing at a time between test runs. Errors are eliminated by making a single change to a script, running it, and seeing how it behaves, then trying to deduce where the error is coming from. Randomly changing your script will make it much harder to pinpoint the source of errors and is unlikely to eliminate them.

Here is an extended example that demonstrates these techniques and introduces some new concepts.


Next topic: Writing a readability analysis program: an example
Previous topic: Solving problems with your script

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005