Chapter 9

Tips on Debugging Scripts

In debugging your scripts, here are some common errors to check. Make
sure you DON'T put a dollar sign before a variable when you're setting
it either using 'set' or '@'.  Make sure you DO put a dollar sign
before a variable anywhere else you want to refer to its value.  Make
sure that you use '@' and not 'set' when you want to do some
arithmetic operations when setting the value of a variable.  Don't
confuse the different ways of quoting expressions.  In particular don't
confuse the backtick operator ` (which is used to force the evaluation
of an expression as in "set x = `ls`" or "foreach file ( `ls` )")
with the single quote which can be used when you want to prevent the
evaluation of variables.  Remember to end every script with a final
carriage return and remember to end every 'while' or 'foreach' loop
with the 'end' keyword. The 'end' keyword should appear on a line all
by itself with no additional spaces.  You can always use 'info csh'
to learn more about the C shell.

If you've carefully checked for all the above problems and your script
is still buggy, the next thing to do is to strategically insert some
diagnostic print statements so you can get some idea of what's going
on in your program as it executes.  For example, if you have a script
that uses the variable 'foo' and the program crashes at some point
where it refers to '$foo', insert 'echo $foo' right before the
statement that you suspect is causing problems.  You can put this sort
of diagnostic print statement anywhere in you program, including
the body of a loop. 

The 'csh' command takes a number of options but two of them are
particularly useful in debugging.  The 'echo' option specified by '-x'
displays each line of the script after variable substitution but
before execution.  The 'verbose' option specified by '-v' displays
each line of the script just as you typed it.  You can use these
options individually or in combination.  You can apply these options
in a number of ways.  You can add them to the directive that appears
at the beginning of a shell script as in:

#!/bin/csh -xv

You can also call 'csh' with these options and the name of the file
containing the script you're trying to debug:

% csh -xv script

You can use 'set' and 'unset' to turn the corresponding shell
variables 'echo' and 'verbose' on and off selectively, for example, in
a particular block of code where you think you have a problem:

% cat script
#!/bin/csh
...
...
set verbose 
set echo 
...
...            <<< suspected problem area
...
unset verbose
unset echo
...
...

Try these two options out so you'll be prepared when you run into a
really nasty bug.