您的位置:首页 > 运维架构 > Shell

shell脚本调试中打开set选项

2014-07-18 16:57 435 查看
设置调试选项概览
短符号长符号结果
set -fset -o noglob禁止特殊字符用于文件名扩展。
set -vset -o verbose打印读入shell的输入行。
set -xset -o xtrace执行命令之前打印命令。
我们在调试shell脚本的时候,不可以避免的会遇到问题,这个时候,假如我们可以跟踪到脚本到底是哪里问了问题,是哪个变量出了问题,这样就对我们的调试是很有帮助的,这里介绍一个shell里面的跟踪选项这里介绍的是set命令,假设在脚本里面加入set
–x ,就能显示脚本运行是的冗余输出,如果在脚本文件中加入了命令set –x ,那么在set命令之后执行的每一条命令以及加载命令行中的任何参数都会显示出来,每一行都会加上加号(+),提示它是跟踪输出的标识,在子shell中执行的shell跟踪命令会加2个叫号(++)。

下面来看看演示脚本:

1:  [root@centos6 shell]# cat set-x.sh

2:  #!/bin/bash

3:  #set -x

4:  echo -n "Can you write device drivers?"

5:  read answer

6:  answer=$(echo $answer | tr [a-z] [A-Z])

7:  if [ $answer = Y ]

8:  then

9:          echo "Wow,you must be very skilled"

10:  else

11:          echo "Neither can I,I am just an example shell script"

12:  fi

13:  [root@centos6 shell]# sh set-x.sh

14:  Can you write device drivers?y

15:  Wow,you must be very skilled

16:  [root@centos6 shell]# sh set-x.sh

17:  Can you write device drivers?n

18:  Neither can I,I am just an example shell script

19:  [root@centos6 shell]#


上面的脚本内容里面,我吧set –x 这一行注释掉了,我们平时都是看到这种效果,下面我将把set –x 这个选项打开,来看看效果:

1:  [root@centos6 shell]# sh set-x.sh

2:  + echo -n 'Can you write device drivers?'

3:  Can you write device drivers?+ read answer

4:  y

5:  ++ echo y

6:  ++ tr '[a-z]' '[A-Z]'

7:  + answer=Y

8:  + '[' Y = Y ']'

9:  + echo 'Wow,you must be very skilled'

10:  Wow,you must be very skilled

11:  [root@centos6 shell]# sh set-x.sh

12:  + echo -n 'Can you write device drivers?'

13:  Can you write device drivers?+ read answer

14:  n

15:  ++ echo n

16:  ++ tr '[a-z]' '[A-Z]'

17:  + answer=N

18:  + '[' N = Y ']'

19:  + echo 'Neither can I,I am just an example shell script'

20:  Neither can I,I am just an example shell script

21:  [root@centos6 shell]#


嘿嘿,看到了吧,每一行都显示出来,每一个参数的状态和执行到哪一步的值是多少,都可以看的很清楚了吧,我们可以很清楚的看到answer这个变量的每一步的状态和值,如果感兴趣,来试验下吧,这个选项
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: