Bash Script Debugging
Basics of Debugging
| Debugging |
| Bash provides two options which will give useful information for debugging
-x : displays each line of the script with variable substitution and before execution. -v : displays each line of the script as typed before execution. |
| Usage: |
| #!/bin/bash –v or #!/bin/bash –x or #!/bin/bash –xv |
| Script |
#!/bin/bash –x echo –n “Enter a number: ”; read x let sum=0 for (( i=1 ; $i<$x ; i=$i+1 )) ; do let “sum = $sum + $i” done echo “the sum of the first $x numbers is: $sum”
|
| The above options can be given explicitly while executing the script |
| bash -x ./script.sh |
| After executing the Script |
+ echo –n ‘Enter a number: ’ Enter a number: + read x 3 + let sum=0 + (( i=0 )) + (( 0<=3 )) + let ‘sum = 0 + 0’ + (( i=0+1 )) + (( 1<=3 )) + let ‘sum = 0 + 1’ + (( i=1+1 )) + (( 2<=3 )) + let ‘sum = 1 + 2’ + (( i=2+1 )) + (( 3<=3 )) + let ‘sum = 3 + 3’ + (( i=3+1 )) + (( 4<=3 )) + echo ‘the sum of the first 3 numbers is: 6’ the sum of the first 3 numbers is: 6
|

| Debugging on part of the scripts | ||
| Using the set Bash built-in you can run in normal mode those portions of the script of which you are sure they are without fault, and display debugging information only for troublesome zones. | ||
| set -x # activate debugging from here
command… command…. …. ….. set +x # stop debugging from here |
||
| The dash is used to activate a shell option and a plus to deactivate it. Don’t let this confuse you! | ||
| You can switch debugging mode on and off as many times as you want within the same script. | ||
| Overview of set debugging options | ||
| Short notation | Long notation | Result |
| set -f | set -o noglob | Disable file name generation using metacharacters (globbing). |
| set -v | set -o verbose | Prints shell input lines as they are read. |
| set -x | set -o xtrace | Print command traces before executing the command. |
| Example : set -f |
ls * commented-scripts.sh script1.sh set –f ls * ls: *: No such file or directory ls commented-scripts.sh script1.sh set +f
|