首页 百科知识 脚本的调试

脚本的调试

时间:2022-10-09 百科知识 版权反馈
【摘要】:Shell提供了多种工具供程序员调试shell脚本。使用带选项的sh、ksh或bash命令可以使脚本文件的调试变得简单,例如,-x选项使shell显示它所执行的每个命令。这样跟踪脚本的执行可以帮助用户发现程序中的错误。使用sh加选项的方式对整个脚本进行调试,若仅对部分脚本内容进行调试,则可以使用set命令。但是,它显示变量替换前的命令行和命令的执行结果。同时使用2个选项使用户能够查看文件中命令执行前后的形式以及其输出结果。

10.8 Shell脚本的调试

在编写shell脚本的过程中难免出现错误,通过对shell脚本的调试,可以寻找及消除这些错误。

Shell提供了多种工具供程序员调试shell脚本。使用带选项的sh、ksh或bash命令可以使脚本文件的调试变得简单,例如,-x选项使shell显示它所执行的每个命令。这样跟踪脚本的执行可以帮助用户发现程序中的错误。在后续例子中使用sh,但用户也可以使用其他shell,如ksh或bash。

sh命令的调试选项有:

-n:读取命令但不执行。

-v:在执行之前,按输入的原样打印脚本中各行。

-x:在变量替换之后、执行命令之前,显示脚本的每一行。

如果想要调试BOX脚本文件,键入如下命令:

$ sh -x BOX [Return]

使用sh加选项的方式对整个脚本进行调试,若仅对部分脚本内容进行调试,则可以使用set命令。命令set –x打开调试跟踪功能,命令set +x关闭调试跟踪功能。

下面使用脚本BOX来说明程序的调试,脚本BOX的内容如下:

$ cat −n BOX

1 # A sample program to show the shell variables

2 echo "The following is output of the $0 script: "

3 echo "Total number of command line arguments: $#"

4 echo "The first parameter is: $1"

5 echo "The second parameter is: $2"

6 echo "This is the list of all parameters: $*"

下面使用带-x选项的sh命令执行BOX脚本文件,但不带命令行参数:

$ sh -x BOX

+ echo The following is the output of the BOX script.

The following is the output of the BOX script.

+ echo Total number of command line arguments: 0

Total number of cummand line arguments: 0

+ echo The first parameter is:

The first parameter is:

+ echo The second parameter is:

The second parameter is:

+ echo This is the list of all parameters:

This is the list of all parameters:

$

上述示例中,以加号(+)开头的行是变量替换后的命令行,它下面的行是命令的输出。

用带-x选项的sh运行BOX,并在命令行上给出一些参数:

$ sh -x BOX of candy

+ echo The following is the output of the BOX script.

The following is the output of the BOX script.

+ echo Total number of command line arguments: 2

Total number of cummand line arguments: 2

+ echo The first parameter is: of

The first parameter is: of

+ echo The second parameter is: candy

The second parameter is: candy

+ echo This is the list of all parameters: of candy

This is the list of all parameters: of candy

$

-v选项与−x选项相似。但是,它显示变量替换前的命令行和命令的执行结果。还可以在一个命令行中同时使用-x和-v选项。同时使用2个选项使用户能够查看文件中命令执行前后的形式以及其输出结果。下面的命令行给出了带这两个选项的sh命令:

$ sh -xv BOX

-n选项用来检查脚本文件中的语法错误。使用该选项,用户可以在运行程序前先检查所写的程序是否有语法错误,例如,假设现有一个名为check_syntax的脚本文件,其中有意包含了语法错误:

$ cat -n check_syntax

1 # A sample program to show the output of the shell -n option

2 echo "$0: checking the program syntax"

3 if [ $# -gt 0 ]

4 # then

5 echo "Number of the command line arguments: $#"

6 else

7 echo "No command line arguments"

8 fi

9 echo "Bye! "

10 exit 0

带-n选项运行check_syntax程序,观察其输出结果:

$ sh -n check_syntax

check_syntax: line 6:syntax error near unexpected token ’else’

$

免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

我要反馈