如何在Unix/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.


来自:linux.chinaunix.net      
1
在Linux中的不少脚本都使用了
set -e
当一个命令不成功,即 $? != 0 时
(不包括  command ||  true, [[ $? != 0 ]] 等 )
脚本就会退出
这是对程序精确控制的要求
避免一些先决条件不充分而导致后边命令的误操作

2
knoppix的开机引导程序有有debug调试功能
大致如下实现
( 在某个需要中断处的代码中 ... )
grep -wq debug /proc/cmdline && /bin/sh

当然如果想在调试的sh中看到你程序中的变量
需要 export 变量名      
sourceforge 上有个比较强的 bash debugger: bashdb, 用法跟 gdb 和 perldb 类似

--
阿亮的签名在 firefox 里面怎么是竖着显示的?      
[quote=dearvoid;569180]sourceforge 上有个比较强的 bash debugger: [URL="http://bashdb.sourceforge.net/"]bashdb[/URL], 用法跟 gdb 和 perldb 类似

--
阿亮的签名在 firefox 里面怎么是竖着显示的?[/quote]
论坛模板问题      
[QUOTE=dearvoid;569180]sourceforge 上有个比较强的 bash debugger: bashdb, 用法跟 gdb 和 perldb 类似

--
阿亮的签名在 firefox 里面怎么是竖着显示的?[/QUOTE]

呵,perldb真不是一般人用的

我还是习惯使用print, echo来看运行情况

另外无人守值的脚本在运行时多打印一些信息
然后记录 STDOUT, STDERR是个不错的主意      
我习惯了图形化debug,F11,F10 之类的按键