在shell脚本中,通过set -x命令进入调试模式,之后Shell除了输出shell执行的结果外,还会输出每行执行的shell命令。

  1 #!/bin/bash
  2 
  3 set -x
  4 
  5 a=1
  6 while [[ $a -le 5 ]]; 
  7 do
  8     echo $a 
  9     let "a+=1"
 10 done

下面的输出中带加号表示该条语句是Shell执行的命令,不带加号表示该语句是Shell产生的输出。

# bash t.sh 
+ a=1
+ [[ 1 -le 5 ]]
+ echo 1
1
+ let a+=1
+ [[ 2 -le 5 ]]
+ echo 2
2
+ let a+=1
+ [[ 3 -le 5 ]]
+ echo 3
3
+ let a+=1
+ [[ 4 -le 5 ]]
+ echo 4
4
+ let a+=1
+ [[ 5 -le 5 ]]
+ echo 5
5
+ let a+=1
+ [[ 6 -le 5 ]]

如果需要中断调试,在调试过程中可以按Ctrl + Z中断调试,观察结果,然后再按fg键继续调试即可。

在shell脚本的开头加上set -x后,会调试整个脚本,有时候可能不需要对整个脚本进行调试,只需要调试某个代码块,那么可以用set -x和set +x把需要调试的代码块包围起来即可,如下

  1 #!/bin/bash
  2 
  3 set -x
  4 
  5 a=1
  6 
  7 function show(){
  8     echo '$a is now =' $1
  9 }
 10 
 11 while [[ $a -le 5 ]]; 
 12 do  
 13     show $a
 14     let "a+=1"
 15 done

这里set -x加在shell脚本的开头,调试的是整个脚本

# bash t.sh 
+ a=1
+ [[ 1 -le 5 ]]
+ show 1
+ echo '$a is now =' 1
$a is now = 1
+ let a+=1
+ [[ 2 -le 5 ]]
+ show 2
+ echo '$a is now =' 2
$a is now = 2
+ let a+=1
+ [[ 3 -le 5 ]]
+ show 3
+ echo '$a is now =' 3
$a is now = 3
+ let a+=1
+ [[ 4 -le 5 ]]
+ show 4
+ echo '$a is now =' 4
$a is now = 4
+ let a+=1
+ [[ 5 -le 5 ]]
+ show 5
+ echo '$a is now =' 5
$a is now = 5
+ let a+=1
+ [[ 6 -le 5 ]]

下面的代码只调试show函数的调用

  1 #!/bin/bash
  2 
  3 a=1
  4 
  5 function show(){
  6     echo '$a is now =' $1
  7 }   
  8 
  9 while [[ $a -le 5 ]]; 
 10 do
 11     set -x
 12     show $a
 13     set +x
 14     let "a+=1"
 15 done

输出如下

# bash t.sh 
+ show 1
+ echo '$a is now =' 1
$a is now = 1
+ set +x
+ show 2
+ echo '$a is now =' 2
$a is now = 2
+ set +x
+ show 3
+ echo '$a is now =' 3
$a is now = 3
+ set +x
+ show 4
+ echo '$a is now =' 4
$a is now = 4
+ set +x
+ show 5
+ echo '$a is now =' 5
$a is now = 5
+ set +x

还记得上面说到的,输出的信息前面有一个+,表示这是shell执行的命令,如果有两个+呢?

  1 #!/bin/bash
  2 
  3 set -x
  4 a=1
  5 echo '$a='$a
  6 echo `ls`

输出如下,看下面的++ ls

# bash t2.sh
+ a=1
+ echo '$a=1'
$a=1
++ ls
+ echo t2.sh t.sh
t2.sh t.sh

输出信息中的++ ls表示这个是在当前shell中启动的子shell中执行的命令。

转载请注明:知识蚂蚁 » linux中的shell调试技术

我来说说

(便于我们更好的交流)

有不明白的地方欢迎留言哦~
取消