shell 脚本调试

Shell:脚本调试

发表于2016/4/27 0:03:30  1693人阅读

分类: Shell

调试功能是每一门编程语言都应该实现的重要特性,每个系统程序员都应该了解Bash的调试选项; 
1.使用选项-x,启动Shell脚本的跟踪调试功能,将执行的每一条命令和输出的结果输出; 
Test.sh文件   
#!/bin/bash 
foriin {1..6}; 
do 
  echo $i 
done 
echo "Script executed"  

正常执行

[pengchengxiang@localhost ~]$ bash test.sh  
1 
2 
… …  
Script executed 
调试执行 

[pengchengxiang@localhost ~]$ bash -x test.sh  
+ foriin '{1..6}' 
+ echo 1 
1 
+ foriin '{1..6}' 
+ echo 2 
2 
… …  
+ echo 'Script executed' 
Script executed 
2.使用set -x和set +x对脚本进行部分调试,将脚本执行的每一行输出到stdout; 

Test.sh文件 

#!/bin/bash 
foriin {1..6}; 
do 
  set -x 
  echo $i 
  set +x 
done 
echo "Script executed" 
部分调试输出 

[pengchengxiang@localhost ~]$ bash -x test.sh  
+ foriin '{1..6}' 
+ set -x 
+ echo 1 
1 
+ set +x 
+ echo 2 
2 
… … 
Script executed 
3.使用自定义格式显示显示信息,通过传递_DEBUG环境变量来建立调试风格; 
Test.sh文件 
#!/bin/bash 
function DEBUG() 
{ 
  [ "$_DEBUG" == "on" ] && $@ || : 
  # “comand1 && command2 || command3”的意思就是如果command1 是成立的,则执行command2,不成立则执行command3.
  #这里的command2 command3都有点特殊。command3是一个冒号:,它表示的意思是啥也不做。command2是 $@,我们记得在shell 脚本执行时,
  #它表示脚本执行的参数列表里的全体参数。在这里它在一个函数里面,表示函数执行时的参数列表里的所有内容。
} 
foriin {1..6}; 
do 
 DEBUG echo $i #可以看到执行DEBUG函数时,可以理解为函数参数是echo $i,那么$@就是函数参数echo $i,也就是说如果如果
                         #[ "$_DEBUG" == "on" ] 则 echo $i,否则 :,即啥也不做 
done echo "Script executed"

正常执行,不输出DEBUG日志信息 
[pengchengxiang@localhost ~]$ ./test.sh  
Script executed 
DEBUG模式执行,输出DEBUG日志信息 
[pengchengxiang@localhost ~]$_DEBUG=on ./test.sh  
1 
2 
3 
4 
5 
6 
Script executed 
4.你也可以在#!/bin/bash -xv,这样就可以不使用任何选项就可以启动调试功能了; 
Test.sh文件 
#!/bin/bash -xv 
function DEBUG() 
{ 
  [ "$_DEBUG" == "on" ] && $@ || : 
} 
 
foriin {1..6}; 
do 
  DEBUG echo $i 
done 
echo "Script executed" 
不添加选项,直接执行 【注意:这种在/bin/bash 后指定 -xv的,只有使用./XXXX.sh的方式才可以看到调试信息,使用sh XXXX.sh看不到调试】
[pengchengxiang@localhost ~]$./test.sh  
#!/bin/bash -xv 
function DEBUG() 
{ 
  [ "$_DEBUG" == "on" ] && $@ || : 
}  
foriin {1..6}; 
do 
  DEBUG echo $i 
done 
+ foriin '{1..6}' 
+ DEBUG echo 1 
+ '[' '' == on ']' 
+ : 
… …  
echo "Script executed" 
+ echo 'Script executed' 
Script executed
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值