46. Shell Script Debugging and GotchasContents:
46.1 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 can just say 46.1.1 Use -xvStart your script like this: #!/bin/sh -xv
(or, if your UNIX can't handle 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 pg
.
But the shell sends its debugging output to stderr
, so I
pipe both stdout
and stderr
(13.4
)
.
Using a pager has another advantage: if you want to kill the script
before it finishes, just use the pager's "quit" command (like q
).
When the pager quits, UNIX may even kill
the shell script (you may see
the message
Do you want to save the debugging output in a file and see it on your screen, too? Use tee (13.9 ) to snag the scrfile stdout and stderr; add tee to the pipeline before the pager. If the script is slow, you can run it in the background. Redirect the shell's output and errors (13.5 , 8.13 ) into a temporary file (21.3 ) . Use tail -f (25.16 ) to "watch" the log file. If you want to do something else while the script runs, just kill the tail command (with CTRL-c or your interrupt key), do something else, then start another tail -f when you want to watch again. Finally, if the script normally writes something to its standard output, you can split the normal and debugging outputs into two files (13.1 ) . 46.1.2 Unmatched Operators
If the shell says 46.1.3 Exit EarlyIf you're getting an echo "DEBUG: quitting early..." 1>&2 exit Then run your script.
Those lines will print a message and stop the shell where you put them.
If you don't get the 46.1.4 Missing or Extra esac, ;;, fi, etc.
A message like 46.1.5 Line Numbers Reset Inside Redirected LoopsThe shell may give you an error that mentions "line 1" or another line number that seems way too small, when there's no error close to the top of your script. Look at any loops or other structures with redirected inputs or outputs (45.22 ) . Some Bourne shells start a separate shell to run these loops and lose track of the line numbers. - |
|