Section 33.1: 使用 -n 检查脚本语法

使用 -n 标志可以检查脚本的语法,而无需执行脚本:

~> $ bash -n testscript.sh
testscript.sh: line 128: unexpected EOF while looking for matching `"'
testscript.sh: line 130: syntax error: unexpected end of file

Section 33.2: 使用 bashdb 调试

Bashdb 是一款类似于 gdb 的工具,可以在某一行或函数中设置断点、打印变量内容、重启脚本执行等。

你通常可以通过软件包管理器安装它,例如在 Fedora 上:

sudo dnf install bashdb

或者从主页上获取。然后,您就可以将脚本作为参数运行它了:

bashdb <YOUR SCRIPT>

下面是几条命令供您参考:

l - show local lines, press l again to scroll down
s - step to next line
print $VAR - echo out content of variable
restart - reruns bashscript, it re-loads it prior to execution.
eval - evaluate some custom command, ex: eval echo hi
b set breakpoint on some line
c - continue till some breakpoint
i b - info on break points
d - delete breakpoint at line #
shell - launch a sub-shell in the middle of execution, this is handy for manipulating variables

如需了解更多信息,建议查阅手册:

http://www.rodericksmith.plus.com/outlines/manuals/bashdbOutline.html

另请参见主页:

http://bashdb.sourceforge.net/

Section 33.3: 使用 -x 调试 bash 脚本

使用 -x 启用已执行行的调试输出。它可以在整个会话或脚本中运行,也可以在脚本中以编程方式启用。

运行已启用调试输出的脚本:

$ bash -x myscript.sh

或者

$ bash --debug myscript.sh

在 bash 脚本中打开调试。调试输出会在脚本退出时自动重置,但可以选择重新打开。

#!/bin/bash
set -x # Enable debugging
# some code here
set +x # Disable debugging output.