使用bash命令参数调试shell脚本

前端之家收集整理的这篇文章主要介绍了使用bash命令参数调试shell脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

首先,bash命令参数说明:

-n:不会执行该脚本,仅查询脚本语法是否有问题,并给出错误提示

-v:在执行脚本时,先将脚本的内容输出到屏幕上,然后执行脚本,如果有错误,也会给错误提示

-x:将执行的脚本内容输出显示到屏幕上。

首先看一段关于-n使用的说明:

  1. root@anLA7856:/home/anla7856/shell# cat while.sh
  2. #!/bin/sh
  3. while true
  4. do
  5. uptime
  6. sleep 2
  7. done
  8. root@anLA7856:/home/anla7856/shell# sh -n while.sh #没有错误
  9. root@anLA7856:/home/anla7856/shell# vi while.sh
  10. root@anLA7856:/home/anla7856/shell# cat while.sh #更改加上一个fu
  11. #!/bin/sh
  12. while true
  13. do
  14. uptime
  15. sleep 2
  16. fu
  17. done
  18. root@anLA7856:/home/anla7856/shell# sh -n while.sh #还是没有说有错误,说明指示针对语法格式检查
  19. root@anLA7856:/home/anla7856/shell# vi while.sh
  20. root@anLA7856:/home/anla7856/shell# sh -n while.sh
  21. while.sh: 8: while.sh: Syntax error: end of file unexpected (expecting "done") #删除了一个done,所以报错了。
  22. root@anLA7856:/home/anla7856/shell# cat while.sh
  23. #!/bin/sh
  24. while true
  25. do
  26. uptime
  27. sleep 2
  28. fu
  29.  

所以-n参数只会检查语法格式是否有问题。


再看-v参数:

  1. root@anLA7856:/home/anla7856/shell# sh -v while.sh
  2. #!/bin/sh
  3. while true #先输出原始脚本内容
  4. do
  5. uptime
  6. sleep 2
  7. done
  8. 10:53:32 up 1:17,1 user,load average: 0.26,0.27,0.26 #再输出结果
  9. 10:53:34 up 1:17,0.26
  10. 10:53:36 up 1:17,load average: 0.24,0.26,0.26
  11. ^C

再看-x参数:
  1. root@anLA7856:/home/anla7856/shell# sh -x while.sh
  2. + true #输出执行脚本的内容输出
  3. + uptime
  4. 10:55:54 up 1:20,load average: 0.41,0.36,0.30 #脚本输出
  5. + sleep 2
  6. + true
  7. + uptime
  8. 10:55:56 up 1:20,load average: 0.37,0.35,0.30
  9. + sleep 2
  10. + true
  11. + uptime
  12. 10:55:58 up 1:20,0.30
  13. + sleep 2
  14. + true
  15. + uptime
  16. 10:56:00 up 1:20,0.30
  17. + sleep 2
  18. + true
  19. + uptime
  20. 10:56:02 up 1:20,load average: 0.34,0.29
  21. + sleep 2


这样的方法是调试整个shell脚本的效果,也可以通过

set命令来调试部分脚本内容

set -n :读命令但并不执行

set -v :显示读取的所有行

set -x :显示所有命令及其参数

主要介绍set -x的例子:

通过:set -x命令开启调试功能,而通过set +x关闭调试功能。即可以细粒度的去调试:

  1. root@anLA7856:/home/anla7856/shell# sh while.sh
  2. + uptime
  3. 11:09:29 up 1:33,load average: 0.31,0.33,0.31
  4. + [ 1 -lt 10 ]
  5. + echo 1
  6. 1
  7. + set +x
  8. + uptime
  9. 11:09:31 up 1:33,load average: 0.28,0.32,0.30
  10. + [ 1 -lt 10 ]
  11. + echo 1
  12. 1
  13. + set +x
  14. ^C
  15. root@anLA7856:/home/anla7856/shell# cat while.sh
  16. #!/bin/sh
  17. num=1
  18. while true
  19. do
  20. set -x
  21. uptime
  22. [ $num -lt 10 ] && echo $num
  23. set +x
  24. sleep 2
  25. done

猜你在找的Bash相关文章