1. 使用bash -x
bash -x打印出脚本执行过程中的所有语句
like:
1 $ bash -x test.sh 2 + echo ----------------begin----------------- 3 ----------------begin----------------- 4 + awk '{sum+=1} END{print sum}' test.sh 5 14 6 + MAX=3 7 + (( i = 0 )) 8 + (( i < MAX ))
配合上注释,bash -x基本可以满足日常80%的需求
2. set
有的时候,我们的脚本非常复杂,使用bash -x得到的输出太多,很难找到需要的信息
set 可以进行局部调试,在需要调试的代码之前加上“set -x”,需要调试的代码之后加上“set +x”即可
like:
修改test.sh:
1 set -x 2 awk '{sum+=1} END{print sum}' test.sh 3 set +x
运行结果:
1 ----------------begin----------------- 2 + awk '{sum+=1} END{print sum}' test.sh 3 16 4 + set +x 5 2013-03-05 6 2013-03-04 7 2013-03-03 8 ----------------end-----------------
3. 使用bash调试工具bashdb(Bash Debugger)
bashdb是一个类GDB的调试工具,使用GDB的同学使用bashdb基本无障碍
bashdb可以运行断点设置、变量查看等常见调试操作
bashdb需要单独安装
使用如下:
1 [root@localhost example]# bashdb --debug example.sh 2 bash debugger, bashdb, release 4.4-1.0.2git 3 4 Copyright 2002-2004, 2006-2012, 2014, 2016-2018 Rocky Bernstein 5 This is free software, covered by the GNU General Public License, and you are 6 welcome to change it and/or distribute copies of it under certain conditions. 7 8 (/home/sl/code/dpipro/restore/indust/example/example.sh:5): 9 5: cd ../../indust/ 10 bashdb<0> n 11 (/home/sl/code/dpipro/restore/indust/example/example.sh:8): 12 8: for dir in $(ls) 13 bashdb<1> n 14 (/home/sl/code/dpipro/restore/indust/example/example.sh:11): 15 11: if [ -d $dir ] 16 bashdb<2> print dir 17 dir 18 bashdb<3> help 19 Available commands: 20 ------------------- 21 action condition edit frame load run source unalias 22 alias continue enable handle next search step undisplay 23 backtrace debug eval help print set step- untrace 24 break delete examine history pwd shell step+ up 25 clear disable export info quit show tbreak watch 26 commands display file kill return signal trace watche 27 complete down finish list reverse skip tty 28 29 Readline command line editing (emacs/vi mode) is available. 30 Type "help" followed by command name for full documentation. 31 bashdb<4>
n:执行下一条语句
print:打印变量值
help:查看bashdb支持的操作命令信息。