转载:http://blog.csdn.net/emmix/article/details/6622135
很少人用到Bash的调试功能吧,大多数通过打印信息来调试。本文主要介绍一下Bash的调试方法。
1 为什么需要调试
2 Bash 调试方法
The shell provides several built-in commands for enabling different modes of debugging support. 类似于C语言的调试,主要分为:
[1] Syntax checking 静态语法检查,同C语言的lint
[2] Shell Tracing
首先我们介绍如何开启Bash的调试方法,然后具体介绍常用每种具体的方法。
2.1 开启调试功能
所有的调试功能打开方式都一样,主要通过两种方式:
[1] 通过给Bash传递选项的方式打开:
# option < {-n -v -x}
/bin/sh option script arg1 arg2 ... argN
#!/bin/sh option
[2] Use the set command in script
# set option
# option < {-n -v -x}
set -x # enable
<the debugging modes are activated>
set +x # disable
set - # All the deugging modes that are enabled for a script can be deactivated using the thiscommand.
set -x ; function; set +x; # only enable the shell tracing debugging mode while that function executes
2.2 Syntax Checking
When dealing with any shell script, check the syntax of the script before trying to execute it. This enables you to fix most problems
#!/bin/sh -n
/bin/sh -n script arg1 arg2 ... argN # -n reads all commands, but does not execute them
#!/bin/sh -nv
/bin/sh -nv script arg1 arg2 ... argN # -v Display all lines as they are read
2.3 Shell Tracing
The shell tracing or execution tracing mode is enabled bby using the -x option (x as in execution).
/bin/sh -x script arg1 arg2 ... argN # -x Displays all commands and their arguments as they execute. This option is often referred to as the shell tracing option
set -x ; ls * ; set +x
2.4 Using Debugging Hooks
Debugging hooks are functions that enable shell tracing during functions or critical code sections. They are activated in one of tow ways: [1] The script is run with a particular command line option ( commonly -d or -x); [2] The script is run with an environment variable set to true ( commonly DEBUG=true or TRACE=true).
Here is a function that enables you to activate and deactivate debuging at willif the variable DEBUG is set to true:
Debug() {
if [ "$DEBUG" = "true" ] ; then
if [ "$1" = "on" -o "$1" = "ON" ] ; then
set -x
else
set +x
fi
fi
}
# function use Debug
Failed() {
Debug on
<----->
Debug off
}
# invoke script
DEBUG=true /bin/sh ./script
DEBUG=true ./script