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.
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 |
(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
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.
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.
3.15.140.68