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" ] && $@ || : 
} 
foriin {1..6}; 
do 
 DEBUG 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" 
不添加选项,直接执行 
[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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值