Scripts written in Bash can also be debugged, just like Python,perl and other interpreted languages. Create a new script named Servinfo and add executable permissions:
Copy Code code as follows:
$ VI Servinfo
#!/bin/bash
echo "Hostname: $ (Hostname)"
echo "Date: $ (date)"
echo "Kernel: $ (Uname-mrs)"
$ chmod +x Servinfo
With Bash-x to debug the above script, bash prints each line of script first, then prints out the results of each line of script:
Copy Code code as follows:
$ bash-x Servinfo
+ + hostname
+ Echo ' Hostname:vpsee '
Hostname:vpsee
+ + Date
+ Echo ' Date:thu Sep 3 19:33:48 sast 2009 '
Date:thu SEP 3 19:33:48 sast 2009
+ + Uname-mrs
+ echo ' kernel:linux 2.6.18-128.4.1.el5 i686 '
Kernel:linux 2.6.18-128.4.1.el5 i686
If you want to print line numbers at the same time, you can add them at the beginning of the script:
Copy Code code as follows:
Export ps4= ' +${bash_source}:${lineno}:${funcname[0]}: '
The results of the execution are:
Copy Code code as follows:
$ bash-x Servinfo
+ Export ' ps4=+${bash_source}:${lineno}:${funcname[0]}: '
+ ps4= ' +${bash_source}:${lineno}:${funcname[0]}: '
++4:5:: hostname
+4:5:: Echo ' Hostname:vpsee '
Hostname:vpsee
++4:6:: Date
+4:6:: Echo ' Date:thu Sep 3 19:42:06 sast 2009 '
Date:thu SEP 3 19:42:06 sast 2009
++4:7:: Uname-mrs
+4:7:: Echo ' kernel:linux 2.6.18-128.4.1.el5 i686 '
Kernel:linux 2.6.18-128.4.1.el5 i686
If you want to debug just a few lines of script, you can include the part you want to debug with Set-x and set +x:
Copy Code code as follows:
#!/bin/bash
echo "Hostname: $ (Hostname)"
Set-x
echo "Date: $ (date)"
Set +x
echo "Kernel: $ (Uname-mrs)"
This time you can run the script directly, no need to perform bash-x:
Copy Code code as follows:
$./servinfo
Hostname:vpsee
+ + Date
+ Echo ' Date:thu Sep 3 19:46:53 sast 2009 '
Date:thu SEP 3 19:46:53 sast 2009
+ Set +x
Kernel:linux 2.6.18-128.4.1.el5 i686
If you want to debug a very complex Bash script, it is recommended that you use specialized debugging tools, such as: Bashdb