Basic Debugging Aids

9.1 Basic Debugging Aids

What sort of functionality do you need to debug a program? At the most empirical level, you need a way of determining what is causing your program to behave badly , and where the problem is in the code. You usually start with an obvious what (such as an error message, inappropriate output, infinite loop, etc.), try to work backwards until you find a what that is closer to the actual problem (e.g., a variable with a bad value, a bad option to a command), and eventually arrive at the exact where in your program. Then you can worry about how to fix it.

Notice that these steps represent a process of starting with obvious information and ending up with often obscure facts gleaned through deduction and intuition. Debugging aids make it easier to deduce and intuit by providing relevant information easily or even automatically, preferably without modifying your code.

The simplest debugging aid (for any language) is the output statement, echo , in the shell's case. Indeed, old-time programmers debugged their FORTRAN code by inserting WRITE cards into their decks. You can debug by putting lots of echo statements in your code (and removing them later), but you will have to spend lots of time narrowing down not only what exact information you want but also where you need to see it. You will also probably have to wade through lots and lots of output to find the information you really want.

9.1.1 Set Options

Luckily, the shell has a few basic features that give you debugging functionality beyond that of echo . The most basic of these are options to the set -o command (as covered in Chapter 3 ). These options can also be used on the command line when running a script, as Table 9.1 shows.

Table 9.1. Debugging Options

set -o Option

Command-Line Option




Don't run commands; check for syntax errors only



Echo commands before running them




Echo commands after command-line processing


The verbose option simply echoes (to standard error) whatever input the shell gets. It is useful for finding the exact point at which a script is bombing . For example, assume your script looks like this:


None of these commands is a standard UNIX program, and each does its work silently. Say the script crashes with a cryptic message like "segmentation violation." This tells you nothing about which command caused the error. If you type bash -v scriptname , you might see this:

 segmentation violation 

Now you know that march is the probable culprit ”though it is also possible that march bombed because of something it expected alice or hatter to do (e.g., create an input file) that they did incorrectly.

The xtrace option is more powerful: it echoes command lines after they have been through parameter substitution, command substitution, and the other steps of command-line processing (as listed in Chapter 7 ). For example:

 .ps 8 
 $  set -o xtrace  $    alice=girl  + alice=girl   
  $   echo "$alice"  + echo girl   
  $   ls -l $(type -path vi)  ++ type -path vi   
  + ls -F -l /usr/bin/vi  
  lrwxrwxrwx 1 root root 5 Jul 26 20:59 /usr/bin/vi -> elvis*  

As you can see, xtrace starts each line it prints with + (each + representing a level of expansion). This is actually customizable: it's the value of the built-in shell variable PS4 . So if you set PS4 to " xtrace ”> " (e.g., in your .bash_profile or .bashrc ), then you'll get xtrace listings that look like this:

 .ps 8 
 $  ls -l $(type -path vi)  xxtrace--> type -path vi   
  xtrace> ls -l /usr/bin/vi  
  lrwxrwxrwx 1 root root 5 Jul 26 20:59 /usr/bin/vi -> elvis*  

Notice that for multiple levels of expansion, only the first character of PS4 is printed. This makes the output more readable.

An even better way of customizing PS4 is to use a built-in variable we haven't seen yet: LINENO , which holds the number of the currently running line in a shell script. [2] Put this line in your .bash_profile or environment file:

[2] In versions of bash prior to 2.0, LINENO won't give you the current line in a function. LINENO , instead, gives an approximation of the number of simple commands executed so far in the current function.

 PS4='line $LINENO: ' 

We use the same technique as we did with PS1 in Chapter 3 : using single quotes to postpone the evaluation of the string until each time the shell prints the prompt. This will print messages of the form line N : in your trace output. You could even include the name of the shell script you're debugging in this prompt by using the positional parameter $0 :

 PS4='$0 line $LINENO: ' 
line $LINENO: '

As another example, say you are trying to track down a bug in a script called alice that contains this code:

 fndrs=$(cut -f3 -d' ' $dfbmq) 

You type alice teatime to run it in the normal way, and it hangs . Then you type bash -x alice teatime , and you see this:

 + dbfmq=teatime.fmq 
 + + cut -f3 -d 

It hangs again at this point. You notice that cut doesn't have a filename argument, which means that there must be something wrong with the variable dbfmq . But it has executed the assignment statement dbfmq=teatime.fmq properly...ah- hah ! You made a typo in the variable name inside the command substitution construct. [3] You fix it, and the script works properly.

[3] We should admit that if you had turned on the nounset option at the top of this script, the shell would have flagged this error.

The last option is noexec , which reads in the shell script, checks for syntax errors, but doesn't execute anything. It's worth using if your script is syntactically complex (lots of loops , command blocks, string operators, etc.) and the bug has side effects (like creating a large file or hanging up the system).

You can turn on these options with set -o option in your shell scripts, and, as explained in Chapter 3 , turn them off with set +o option . For example, if you're debugging a chunk of code, you can precede it with set -o xtrace to print out the executed commands, and end the chunk with set +o xtrace .

Note, however, that once you have turned noexec on, you won't be able to turn it off; a set +o noexec will never be executed.

9.1.2 Fake Signals

A more sophisticated set of debugging aids is the shell's "fake signals," which can be used in trap statements to get the shell to act under certain conditions. Recall from the previous chapter that trap allows you to install some code that runs when a particular signal is sent to your script.

Fake signals work in the same way, but they are generated by the shell itself, as opposed to the other signals which are generated externally. They represent runtime events that are likely to be of interest to debuggers ”both human ones and software tools ”and can be treated just like real signals within shell scripts. Table 9.2 lists the two fake signals available in bash .

Table 9.2. Fake Signals

Fake Signal

Sent When


The shell exits from script


The shell has executed a statement a


[4] The DEBUG signal is not available in bash versions prior to 2.0. EXIT

The EXIT trap, when set, will run its code whenever the script within which it was set exits. [5]

[5] You can trap only the exiting of a script. Functions don't generate the EXIT signal, as they are part of the current shell invocation.

Here's a simple example:

 trap 'echo exiting from the script' EXIT 
 echo 'start of the script' 

If you run this script, you will see this output:

 start of the script 
 exiting from the script 

In other words, the script starts by setting the trap for its own exit, then prints a message. The script then exits, which causes the shell to generate the signal EXIT, which in turn runs the code echo exiting from the script .

An EXIT trap occurs no matter how the script exits ”whether normally (by finishing the last statement), by an explicit exit or return statement, or by receiving a "real" signal such as INT or TERM . Consider this inane number-guessing program:

 trap 'echo Thank you for playing!' EXIT 
 echo 'Guess a number between 1 and 10:' 
 while read -p 'Guess: ' guess ; do 
 sleep 4 
 if [ "$guess" = $magicnum ]; then 
 echo 'Right!' 
 echo 'Wrong!' 

This program picks a number between 1 and 10 by getting a random number (the built-in variable RANDOM ), extracting the last digit (the remainder when divided by 10), and adding 1. Then it prompts you for a guess, and after 4 seconds, it will tell you if you guessed right.

If you did, the program will exit with the message, "Thank you for playing!", i.e., it will run the EXIT trap code. If you were wrong, it will prompt you again and repeat the process until you get it right. If you get bored with this little game and hit CTRL-C or CTRL-D while waiting for it to tell you whether you were right, you will also see the message.

The EXIT trap is especially useful when you want to print out the values of variables at the point that your script exits. For example, by printing the value of loop counter variables , you can find the most appropriate places in a complicated script, with many nested for loops, to enable xtrace or place debug output. DEBUG

The other fake signal, DEBUG, causes the trap code to be executed after every statement in a function or script. This has two main uses. First is the use for humans , as a sort of "brute force" method of tracking a certain element of a program's state that you notice has gone awry.

For example, you notice the value of a particular variable is running amok. The naive approach is to put in a lot of echo statements to check the variable's value at several points. The DEBUG trap makes this easier by letting you do this:

  function dbgtrap  
  echo "   badvar    is    badvar    "   
   trap dbgtrap DEBUG   
   ...section of code in which the problem occurs...   
   trap - DEBUG # turn off the DEBUG trap   

This code will print the value of the wayward variable after every statement between the two trap s.

One important point to remember when using DEBUG is that it is not inherited by functions called from the shell in which it is set. In other words, if your shell sets a DEBUG trap and then calls a function, the statements within the function will not execute the trap. You have to set a trap for DEBUG explicitly within the function if you want to use it.

The second and far more important use of the DEBUG signal is as a primitive for implementing a bash debugger. In fact, it would be fair to say that DEBUG reduces the task of implementing a useful shell debugger from a large-scale software development project to a manageable exercise.


Learning the Bash Shell
Learning the bash Shell: Unix Shell Programming (In a Nutshell (OReilly))
ISBN: 0596009658
EAN: 2147483647
Year: 1998
Pages: 104

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: