天下网吧 >> 网吧天地 >> 网吧技术 >> 网吧系统 >> 正文

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

2008-4-8赛迪网佚名

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.

欢迎访问最专业的网吧论坛,无盘论坛,网吧经营,网咖管理,网吧专业论坛https://bbs.txwb.com

关注天下网吧微信,了解网吧网咖经营管理,安装维护:


本文来源:赛迪网 作者:佚名

声明
本文来源地址:0
声明:本站所发表的文章、评论及图片仅代表作者本人观点,与本站立场无关。若文章侵犯了您的相关权益,请及时与我们联系,我们会及时处理,感谢您对本站的支持!联系Email:support@txwb.com.,本站所有有注明来源为天下网吧或天下网吧论坛的原创作品,各位转载时请注明来源链接!
天下网吧·网吧天下
  • 本周热门
  • 本月热门
  • 阅读排行