帮助中心 >  技术知识库 >  云服务器 >  服务器教程 >  如何在 Shell 脚本中执行语法检查调试模式

如何在 Shell 脚本中执行语法检查调试模式

2017-01-19 15:43:49 6047

-n 激活语法检查模式。它会让 shell 读取所有的命令,但是不会执行它们,它(shell)只会检查语法。

一旦 shell 脚本中发现有错误,shell 会在终端中输出错误,不然就不会显示任何东西。

激活语法检查的命令如下:

$ bash -n script.sh

因为脚本中的语法是正确的,上面的命令不会显示任何东西。所以,让我们尝试删除结束 for 循环的 done 来看下是否会显示错误:

下面是修改过的含? bug 的批量将 png 图片转换成 jpg 格式的脚本。

#!/bin/bash#script with a bug#convertfor image in *.png; doconvert  "$image"  "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"exit 0

保存文件,接着运行该脚本并执行语法检查:

$ bash -n script.sh

Check Syntax in Shell Script

检查 shell 脚本语?

从上面的输出中,我们看到我们的脚本中有一个错误,for 循环缺少了一个结束的 done 关键字。shell 脚本从头到尾检查文件,一旦没有找到它(done),shell 会打印出一个语法错误:

script.sh: line 11: syntax error: unexpected end of file

我们可以同时结合 verbose 模式和语法检查模式:

$ bash -vn script.sh

Enable Verbose and Syntax Checking in Script

在脚本中同时启用 verbose 检查和语法检查

另外,我们可以通过修改脚本的首行来启用脚本检查,如下面的例子:

#!/bin/bash -n#altering the first line of a script to enable syntax checking#convertfor image in *.png; doconvert  "$image"  "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"exit 0

如上所示,保存文件并在运行中检查语法:

$ ./script.shscript.sh: line 12: syntax error: unexpected end of file

此外,我们可以用内置的 set 命令来在脚本中启用调试模式。

下面的例子中,我们只检查脚本中的 for 循环语法。

#!/bin/bash#using set shell built-in command to enable debugging#convert#enable debuggingset -nfor image in *.png; doconvert  "$image"  "${image%.png}.jpg"echo "image $image converted to ${image%.png}.jpg"#disable debuggingset +nexit 0

再一次保存并执行脚本:

$ ./script.sh


提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: