Previous Section  < Day Day Up >  Next Section

14.9. Debugging

By using the –n option to the bash command, you can check the syntax of your scripts without really executing any of the commands. If there is a syntax error in the script, the shell will report the error. If there are no errors, nothing is displayed.

The most commonly used method for debugging scripts is the set command with the –x option, or bash invoked with the –x option and the script name. See Table 14.7 for a list of debugging options. These options allow an execution trace of your script. Each command from your script is displayed after substitution has been performed, and then the command is executed. When a line from your script is displayed, it is preceded with a plus (+) sign.

Table 14.7. Debugging Options

Command

Option

What It Does

bash –x scriptname

Echo option

Displays each line of script after variable substitutions and before execution.

bash –v scriptname

Verbose option

Displays each line of script before execution, just as you typed it.

bash –n scriptname

Noexec option

Interprets but does not execute commands.

set –x

Turns on echo

Traces execution in a script.

set +x

Turns off echo

Turns off tracing.


With the verbose option turned on, or by invoking the shell with the –v option (bash –v scriptname), each line of the script will be displayed just as it was typed in the script, and then executed. (See Chapter 15, "Debugging Shell Scripts," on page 967 for details.)

Example 14.69.

(The Script)

    #!/bin/bash

    # Scriptname: todebug



1   name="Joe Shmoe"

    if [[ $name == "Joe Blow" ]]

    then

        printf "Hello $name\n"

    fi



    declare -i num=1

    while (( num < 5 ))

    do

       let num+=1

    done

    printf "The total is %d\n", $num



(The Output)

2 bash -x todebug

+ name=Joe Shmoe

+ [[ Joe Shmoe == \J\o\e\ \B\l\o\w ]]

+ declare -i num=1

+ ((  num < 5  ))

+ let num+=1

+ ((  num < 5  ))

+ let num+=1

+ ((  num < 5  ))

+ let num+=1

+ ((  num < 5  ))

+ let num+=1

+ ((  num < 5  ))

+ printf 'The total is %d\n,' 5

The total is 5


EXPLANATION

  1. The script is called todebug. You can watch the script run with the –x switch turned on. Each iteration of the loop is displayed and the values of variables are printed as they are set and when they change.

  2. Bash is invoked with the –x option. Echoing is turned on. Each line of the script will be displayed to the screen prepended with a plus sign (+). Variable substitution is performed before the line is displayed. The result of the execution of the command appears after the line has been displayed.

    Previous Section  < Day Day Up >  Next Section