bash脚本调试方法介绍

 

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支持的操作命令信息。 

 

 

 

4. bashdb常用指令

 1.列出代码和查询代码指令

1 l  列出当前行以下的10行
2 -  列出正在执行的代码行的前面10行
3 .  回到正在执行的代码行
4 w  列出正在执行的代码行前后的代码
5 /pat/ 向后搜索pat
6 ?pat?向前搜索pat

2.debug空值指令

1 h 帮助
2 help 命令 得到命令的具体信息
3 q 退出bashdb
4 x 算数表达式  计算算数表达式的值,并显示出来
5 !! Shell命令  执行shell命令

3.控制脚本执行指令

1 n 执行下一条语句,遇到函数,不进入函数里面执行,将函数当作黑盒
2 s n 单步执行n次,遇到函数进入函数里面
3 b 行号n  在行号n处设置断点
4 del 行号n   撤销行号n处的断点
5 c 行号n   一直执行到行号n处
6 R 重新启动当前调试脚本
7 Finish 执行到程序最后
8 cond n expr 条件断点
posted @ 2019-12-03 17:21  凌空a  阅读(1097)  评论(0编辑  收藏  举报