调试功能是每一门编程语言都应该实现的重要特性,每个系统程序员都应该了解Bash的调试选项;
1.使用选项-x,启动Shell脚本的跟踪调试功能,将执行的每一条命令和输出的结果输出;
Test.sh文件
Test.sh文件
Test.sh文件
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