网站搜索

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


我们通过解释不同的调试选项以及如何启用 shell 脚本调试模式来开始 shell 脚本调试系列。

编写 shell 脚本后,建议我们在运行脚本之前实际检查脚本中的语法,而不是查看其输出来确认它们是否正常工作。

在本系列的这一部分中,我们将介绍如何使用语法检查调试模式。请记住,我们在本系列的第一部分中解释了不同的调试选项,在这里,我们将使用它们来执行脚本调试。

启用详细调试模式

在我们转向本指南的主要焦点之前,让我们简要探讨一下详细模式。它由 -v 调试选项启用,该选项告诉 shell 在读取脚本时显示脚本中的所有行。

为了演示其工作原理,下面是一个示例 shell 脚本,用于将 PNG 图像批量转换为 JPG 格式。

将其键入(或复制并粘贴)到文件中。

#!/bin/bash
#convert
for image in *.png; do
        convert  "$image"  "${image%.png}.jpg"
        echo "image $image converted to ${image%.png}.jpg"
done
exit 0

然后保存文件并使用以下命令使脚本可执行:

chmod +x script.sh

我们可以调用脚本并显示 shell 读取其中的所有行,如下所示:

bash -v script.sh

在 Shell 脚本中启用语法检查调试模式

回到我们强调的主题,-n 激活语法检查模式。它指示 shell 基本上读取所有命令,但不执行它们,它(shell)仅检查所使用的语法。

如果 shell 脚本中有错误,shell 会在终端上输出错误,否则不显示任何内容。

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

bash -n script.sh

由于脚本中的语法是正确的,因此上面的命令不会显示任何输出。因此,让我们尝试删除关闭 for 循环的 done 单词,看看它是否显示错误:

下面是修改后的批量将 png 图像转换为 jpg 格式的 shell 脚本,其中包含一个错误。

#!/bin/bash
#script with a bug
#convert
for image in *.png; do
        convert  "$image"  "${image%.png}.jpg"
        echo "image $image converted to ${image%.png}.jpg"

exit 0

保存文件,然后运行它,同时在其中执行语法检查:

bash -n script.sh

从上面的输出中,我们可以看到我们的脚本存在语法问题,for 循环缺少结束关键字 done 。 shell 一直查找到文件末尾,一旦没有找到(done),shell 就会打印一个语法错误:

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

我们也可以将详细模式和语法检查模式结合在一起:

bash -vn script.sh

或者,我们可以通过修改上面脚本的第一行来启用语法检查,如下一个示例所示。

#!/bin/bash -n
#altering the first line of a script to enable syntax checking

#convert
for image in *.png; do
    convert  "$image"  "${image%.png}.jpg"
    echo "image $image converted to ${image%.png}.jpg"

exit 0

和以前一样,保存文件并在执行语法检查时运行它:

./script.sh

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

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

在下面的示例中,我们仅检查脚本中 for 循环的语法。

#!/bin/bash
#using set shell built-in command to enable debugging
#convert

#enable debugging
set -n
for image in *.png; do
    convert  "$image"  "${image%.png}.jpg"
    echo "image $image converted to ${image%.png}.jpg"

#disable debugging
set +n
exit 0

再次保存文件并调用脚本:

./script.sh 

总之,我们应该始终确保在执行 shell 脚本之前对它们进行语法检查以捕获任何错误。

要向我们发送有关本指南的任何问题或反馈,请使用下面的回复表。在本系列的第三部分中,我们将转向解释和使用 shell 跟踪调试模式。