深入Bash___调试

转载: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值