当前位置:编程学习 > 网站相关 >>

bash调试经验

 
以下使用一个测试脚本来说明使用bash调试的方法
test.sh
[plain] view plaincopy
#!/bin/bash  
  
echo "----------------begin-----------------"  
  
awk '{sum+=1} END{print sum}' test.sh  
  
MAX=3  
for ((i = 0; i < MAX; i++))  
do  
        loaddate=`date -d"-$i day" +%Y-%m-%d`  
        echo $loaddate  
done  
  
echo "----------------end-----------------"  
 
1. 使用bash -x
bash -x打印出脚本执行过程中的所有语句
like:
$ bash -x test.sh 
+ echo ----------------begin-----------------
----------------begin-----------------
+ awk '{sum+=1} END{print sum}' test.sh
14
+ MAX=3
+ (( i = 0 ))
+ (( i < MAX ))
++ date '-d-0 day' +%Y-%m-%d
+ loaddate=2013-03-05
+ echo 2013-03-05
2013-03-05
+ (( i++ ))
+ (( i < MAX ))
++ date '-d-1 day' +%Y-%m-%d
+ loaddate=2013-03-04
+ echo 2013-03-04
2013-03-04
+ (( i++ ))
+ (( i < MAX ))
++ date '-d-2 day' +%Y-%m-%d
+ loaddate=2013-03-03
+ echo 2013-03-03
2013-03-03
+ (( i++ ))
+ (( i < MAX ))
+ echo ----------------end-----------------
----------------end-----------------
配合上注释,bash -x基本可以满足日常80%的需求
 
2. set 
有的时候,我们的脚本非常复杂,使用bash -x得到的输出太多,很难找到需要的信息
set 可以进行局部调试,在需要调试的代码之前加上“set -x”,需要调试的代码之后加上“set +x”即可
like:
修改test.sh:
....
set -x
awk '{sum+=1} END{print sum}' test.sh
set +x
.....
运行:
----------------begin-----------------
+ awk '{sum+=1} END{print sum}' test.sh
16
+ set +x
2013-03-05
2013-03-04
2013-03-03
----------------end-----------------
 
3. 使用bash调试工具bashdb(Bash Debugger)
bashdb是一个类GDB的调试工具,使用GDB的同学使用bashdb基本无障碍
bashdb可以运行断点设置、变量查看等常见调试操作
bashdb需要单独安装
使用如下:
$ bashdb --debug test.sh            
bash debugger, bashdb, release 4.2-0.8
 
 
Copyright 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Rocky Bernstein
This is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
 
 
(/home/work/code/test.sh:3):
3:      echo "----------------begin-----------------"
bashdb<0> n  #下一步
----------------begin-----------------
(/home/work/code/test.sh:5):
5:      awk '{sum+=1} END{print sum}' test.sh
bashdb<1> l #列出上下共10行代码
  1:    #!/bin/bash
  2:    
  3:    echo "----------------begin-----------------"
  4:    
  5: => awk '{sum+=1} END{print sum}' test.sh
  6:    
  7:    MAX=3
  8:    for ((i = 0; i < MAX; i++))
  9:    dowww.zzzyk.com
 10:            loaddate=`date -d"-$i day" +%Y-%m-%d`
bashdb<2> b 10 #第10行设置断点
Breakpoint 1 set in file /home/work/code/test.sh, line 10.
bashdb<3> c #继续运行
14
Breakpoint 1 hit (1 times).
(/home/work/code/test.sh:10):
10:             loaddate=`date -d"-$i day" +%Y-%m-%d`
bashdb<4> print $i #打印变量值
0
 14:    echo "----------------end-----------------"
补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,