Debugging Shell Programs


Quite often you will find that your shell scripts don’t work the way you expect when you try to run them. It is easy to enter a typo, or to leave out necessary quotation marks or escape characters, in the first draft of a script. A typo in a shell script will usually cause the script to stop running when it gets to the error, but in some cases the script will skip over the error and continue execution. Occasionally this can cause serious problems. For example, if you attempt to copy and then delete a file with

 copy oldfile newfile rm oldfile

the copy will fail (because the command is named cp), but rm will still remove oldfile.

The best way to prevent frustrating errors is to test your scripts frequently as you write them, as opposed to writing a very long script all at once and then attempting to run it. It is also a good idea to run your scripts on test files or data before using them on important information.

A script that does not run will often provide an error message on the screen. For example,

 prog: syntax error at line 12: 'do' unmatched

or

 prog: syntax error at line 142: 'end of file' unexpected

These error messages function as broad hints that you have made an error. Several shell key words are used in pairs, for example, if ... fi, case ... esac, and do ... done. This type of message tells you that an unmatched pair exists, although it does not tell you where it is. Since it is difficult to tell how word pairs such as do ... done were intended to be used, the shell informs you that a mismatch occurred, not where it was. The do unmatched at line 12 may be missing a done at line 142, but at least you know what kind of problem to track down.

The next thing to do if you are having trouble with a script is to watch it while each line of the script is executed. The command

 $ sh -x filename

tells the shell to run the script in filename, printing each command and its arguments as it is executed. Because the most common errors in scripts have to do with unmatched keywords, incorrect quotation marks (e.g., ‘rather than’), and improperly set variables, sh -x reveals most of your early errors. At the very least, sh -x can help you determine where in your script things start to go wrong.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net