用 Bash 写的脚本也可以进行调试,和 Python,Perl 等解释型语言一样。新建一个名为 servinfo 的脚本并增加可执行权限:
$ vi servinfo.sh #!/bin/bash #demo for debug shell echo "Hostname :$(hostname)" echo "Date:$(date)" echo "Kernel:$(uname -mrs)" $ chmod +x servinfo.sh |
用bash -x 或者sh -x 来调试上述脚本servinfo.sh,Bash先打印出每行脚本,再打印出每行脚本的执行结果:
$ bash -x servinfo.sh ++ hostname + echo 'Hostname :ubuntu' Hostname :ubuntu ++ date + echo 'Date:Wed Nov 23 23:21:39 CST 2011' Date:Wed Nov 23 23:21:39 CST 2011 ++ uname -mrs + echo 'Kernel:Linux 2.6.24-22-generic x86_64' Kernel:Linux 2.6.24-22-generic x86_64 |
如果想同时打印行号的话,可以在脚本开头加上:
export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: ' |
$ bash -x servinfo.sh + export 'PS4=+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: ' + PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: ' ++servinfo.sh:4:: hostname +servinfo.sh:4:: echo 'Hostname :ubuntu' Hostname :ubuntu ++servinfo.sh:5:: date +servinfo.sh:5:: echo 'Date:Wed Nov 23 23:29:22 CST 2011' Date:Wed Nov 23 23:29:22 CST 2011 ++servinfo.sh:6:: uname -mrs +servinfo.sh:6:: echo 'Kernel:Linux 2.6.24-22-generic x86_64' Kernel:Linux 2.6.24-22-generic x86_64 |
如果只想调试其中几行脚本的话可以用 set -x 和 set +x 把要调试的部分包含进来:
#!/bin/bash #demo for debug shell echo "Hostname :$(hostname)" set -x echo "Date:$(date)" set +x echo "Kernel:$(uname -mrs)" |
运行结果如下:
$ sh servinfo.sh Hostname :ubuntu + date + echo Date:Wed Nov 23 23:31:05 CST 2011 Date:Wed Nov 23 23:31:05 CST 2011 + set +x Kernel:Linux 2.6.24-22-generic x86_64 |