首先,bash命令参数说明:
-n:不会执行该脚本,仅查询脚本语法是否有问题,并给出错误提示。
-v:在执行脚本时,先将脚本的内容输出到屏幕上,然后执行脚本,如果有错误,也会给错误提示。
首先看一段关于-n使用的说明:
- root@anLA7856:/home/anla7856/shell# cat while.sh
- #!/bin/sh
- while true
- do
- uptime
- sleep 2
- done
- root@anLA7856:/home/anla7856/shell# sh -n while.sh #没有错误
- root@anLA7856:/home/anla7856/shell# vi while.sh
- root@anLA7856:/home/anla7856/shell# cat while.sh #更改加上一个fu
- #!/bin/sh
- while true
- do
- uptime
- sleep 2
- fu
- done
- root@anLA7856:/home/anla7856/shell# sh -n while.sh #还是没有说有错误,说明指示针对语法格式检查
- root@anLA7856:/home/anla7856/shell# vi while.sh
- root@anLA7856:/home/anla7856/shell# sh -n while.sh
- while.sh: 8: while.sh: Syntax error: end of file unexpected (expecting "done") #删除了一个done,所以报错了。
- root@anLA7856:/home/anla7856/shell# cat while.sh
- #!/bin/sh
- while true
- do
- uptime
- sleep 2
- fu
所以-n参数只会检查语法格式是否有问题。
再看-v参数:
再看-x参数:
- root@anLA7856:/home/anla7856/shell# sh -x while.sh
- + true #输出执行脚本的内容输出
- + uptime
- 10:55:54 up 1:20,load average: 0.41,0.36,0.30 #脚本输出
- + sleep 2
- + true
- + uptime
- 10:55:56 up 1:20,load average: 0.37,0.35,0.30
- + sleep 2
- + true
- + uptime
- 10:55:58 up 1:20,0.30
- + sleep 2
- + true
- + uptime
- 10:56:00 up 1:20,0.30
- + sleep 2
- + true
- + uptime
- 10:56:02 up 1:20,load average: 0.34,0.29
- + sleep 2
set命令来调试部分脚本内容。
set -n :读命令但并不执行
set -v :显示读取的所有行
set -x :显示所有命令及其参数
主要介绍set -x的例子:
通过:set -x命令开启调试功能,而通过set +x关闭调试功能。即可以细粒度的去调试:
- root@anLA7856:/home/anla7856/shell# sh while.sh
- + uptime
- 11:09:29 up 1:33,load average: 0.31,0.33,0.31
- + [ 1 -lt 10 ]
- + echo 1
- 1
- + set +x
- + uptime
- 11:09:31 up 1:33,load average: 0.28,0.32,0.30
- + [ 1 -lt 10 ]
- + echo 1
- 1
- + set +x
- ^C
- root@anLA7856:/home/anla7856/shell# cat while.sh
- #!/bin/sh
- num=1
- while true
- do
- set -x
- uptime
- [ $num -lt 10 ] && echo $num
- set +x
- sleep 2
- done