linux初探

首页

应用服务器

Linux技巧

中文文档

Linux初级

服务器源代码

命令详解

Linux技术应用

Linux安全应用

Linux业界新闻

UniX技术文章

Linux编程与内核

Linux数据库

Linux服务器

Linux安装指导

Linux论坛

首页>>Linux编程与内核>>文章正文

在Unix/Linux系统下调试脚本程序

command
Bash shell offers debugging options which can be turn on or off using set command.
=> set -x : Display commands and their arguments as they are executed.
=> set -v : Display shell input lines as they are read.

You can use above two command in shell script itself:

#!/bin/bash
clear
# turn on debug mode
set -x
for f in *
do
file $f
done
# turn OFF debug mode
set +x
ls
# more commands

You can replace standard
#!/bin/bash
with (for debugging)
#!/bin/bash -xv

Method # 3: Use of intelligent DEBUG function
Add special variable _DEBUG. Set to `on’ when you need to debug a script:
_DEBUG="on"

Put the following function at the beginning of the script:

function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@ || :
}
Now wherever you need debugging simply use DEBUG function
DEBUG echo "File is $filename"
OR
DEBUG set -x
Cmd1
Cmd2
DEBUG set +x


When debugging done and before moving a script to production set _DEBUG to off
No need to delete debug lines.
_DEBUG="off" # set to anything but not to 'on'

Sample script:

#!/bin/bash
_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@ || :
}

DEBUG echo 'Reading files'
for i in *
do
grep 'something' $i > /dev/null
[ $? -eq 0 ] && echo "Found in $i file" || :
done
DEBUG set -x
a=2
b=3
c=$(( $a + $b ))
DEBUG set +x
echo "$a + $b = $c"

Save and run the script:
$ ./script.sh
Output:

Reading files
Found in xyz.txt file
+ a=2
+ b=3
+ c=5
+ DEBUG set +x
+ '[' on == on ']'
+ set +x
2 + 3 = 5

Now set DEBUG to off
_DEBUG="off"
Run script:
$ ./script.sh
Output:

Found in xyz.txt file
2 + 3 = 5

Above is a simple but quite effective technique. You can also try to use DEBUG as an alias instead of function.

相关文章

·SHELL利用的各种初期化文件
·Shell的特点
·Shell脚本的建立
·升级和编译你的Linux核心
·tmpfile函数
·Shell, Sqlite,date和awk
·我爱linux
·linux内核时间,延迟,和延缓操作
·Linux下的Matlab使用syms出错的问题

热门文章

·C++中控制Windows关机的实用
·C++继承性应用实例 日期和时
·C++类型转换时定义非成员函数
·从模板中分离出参数无关的代
·C++中用函数模板实现和优化抽
·用C++ Builder检测Windows的
·用C++ Builder来定制系统菜单
·C++语言代码检查工具PC-Lint
·用C语言实现常见的三种中文内
·用C++ Builder开发多层数据库

Copyright@2005 www.linuxGoo.com All Right Reserved