使用bash命令参数调试shell脚本
发布时间:2020-12-15 16:22:39 所属栏目:安全 来源:网络整理
导读:首先,bash命令参数说明: -n:不会执行该脚本,仅查询脚本语法是否有问题,并给出错误提示。 -v:在执行脚本时,先将脚本的内容输出到屏幕上,然后执行脚本,如果有错误,也会给错误提示。 -x:将执行的脚本内容及输出显示到屏幕上。 首先看一段关于-n使用
首先,bash命令参数说明: -n:不会执行该脚本,仅查询脚本语法是否有问题,并给出错误提示。 -v:在执行脚本时,先将脚本的内容输出到屏幕上,然后执行脚本,如果有错误,也会给错误提示。 -x:将执行的脚本内容及输出显示到屏幕上。 首先看一段关于-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参数: root@anLA7856:/home/anla7856/shell# sh -v while.sh #!/bin/sh while true #先输出原始脚本内容 do uptime sleep 2 done 10:53:32 up 1:17,1 user,load average: 0.26,0.27,0.26 #再输出结果 10:53:34 up 1:17,0.26 10:53:36 up 1:17,load average: 0.24,0.26,0.26 ^C 再看-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
这样的方法是调试整个shell脚本的效果,也可以通过 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |