Chapter 37. Shell Script Debugging and Gotchas
Tips for Debugging Shell Scripts
Depending on the Bourne shell version you
have, the error messages it gives can be downright useless. For instance, it
might say just
unexpected. Here are a few tricks to use to
get a little more information about what’s going on. Remember, it’s probably
best for you to use one of shells derived from the Bourne shell, rather than the
C shell, for scripting.
Start your script like this:
your Unix can’t handle
#!, use the
command set -xv (Section 35.25)). The
-xv shows you what’s happening as the shell
reads your script. The lines of the script will be shown as the shell reads
them. The shell shows each command it executes with a plus sign (
+) before the command.
Note that the shell reads an entire loop (for, while, etc.) before it executes any commands in the loop.
If you want to run a script with debugging but you don’t want to edit the script file, you can also start the shell explicitly from the command line and give the options there:
Debugging output is usually pretty long, more than a screenful, so I pipe it to a pager like less. But the shell sends its debugging output to stderr, so I pipe both stdout and stderr (Section 43.4) to the pager.
2>&1 | less
Do you want to save the debugging output in a file and see it on your screen, too? Use tee (Section 43.8) to copy the scrfile stdout and stderr; add tee to the pipeline before the pager. ...