9.9. Debugging

By using the -n option to the bash command, you can check the sytnax 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 scriptname. See Table 9.7 on page 465 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.

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.

Table 9.7. Debugging Options
CommandOptionWhat It Does
bash -x scriptnameEcho optionDisplays each line of script after variable substitutions and before execution
bash -v scriptnameVerbose optionDisplays each line of script before execution, just as you typed it
bash -n scriptnameNoexec optionInterprets but does not execute commands
set -xTurns on echoTraces execution in a script
set +xTurns off echoTurns off tracing

Example 9.69.
(The Script)
$ cat todebug
   #!/bin/bash
   # Scriptname: todebug
1  name="Joe Shmoe"
   if [[ $name == "Joe Blow" ]]
   then
        printf "Hello $name
"
   fi
   declare -i num=1
   while (( num < 5 ))
   do
        let num+=1
   done
   printf "The total is %d
", $num

(The Output)
2 bash -x todebug
+ name=Joe Shmoe
+ [[ Joe Shmoe == Joe Blow ]]
+ 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
,' 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.140.68