如何使用 gdb 调试 Bourne Shell?

How can I debug the Bourne Shell with gdb?

我构建了一个工具链脚本来准备 Linux 构建环境。该脚本可以在这里找到:https://github.com/mynameismevin/prometheus/blob/toolchain/ptool-make.sh

脚本 运行 在第 416 行附近的 Perl 部分之后完美运行。Perl 完成后,当它去解压缩 sed 时,它会报错:

tar (child): sed-4.2.2.tar.bz2: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now

但是,如果我 运行 手动选择这些部分,它会毫无错误地完成。如果我将脚本拆分为 ptool-make1.sh(以 Perl 结束)和 ptool-make2.sh(以 sed 开始)和 运行,那么它们都可以毫无问题地完成。在这一点上,我断言问题不在于脚本,我想调试 shell 以查看它是否是 shell.

的问题

这里有一些有用的配置:

user@ubuntu:~$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.2 LTS"
user@ubuntu:~$ bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
user@ubuntu:~$ ls -lh $(which bash)
-rwxr-xr-x 1 root root 998K Oct  7  2014 /bin/bash

我不认为 Ubuntu bash 带有调试符号,所以我假设我必须重新编译才能包含这些符号?

当我 运行 脚本时,如何使用 gdb 调试 shell?或者我如何在脚本 运行s 时将 shell 记录到文件中,以便在完成后用 gdb 打开它?我知道如何调试 shell 脚本,我不想调试脚本,我想调试 shell.

编辑:看起来 Ubuntu bash 没有开箱即用的调试符号。 Reading symbols from bash...(no debugging symbols found)...done.

编辑:$PROMETHEUS 设置在我的根 shell 中。在 Perl 的末尾 cd .. 产生相同的结果 cd $PROMETHEUS/sources/.

Shell 带有自己的调试工具。最简单的是 运行 将它们与 -x (bash -x ...script...) 结合起来,这将在变量扩展之后但在执行之前打印每个命令。这通常足以确定问题。

有关更多想法,请参阅 How to debug a bash script?

您还应该考虑编写辅助函数以将脚本的大小减少到几行。您可以将特殊选项移动到配置或 post-build 步骤到额外的文件中,并且 运行 它们来自辅助函数(如果它们存在)。

查看代码,似乎这一行是罪魁祸首:

cd $PROMETHEUS/sources/

在其他任何地方,您只需使用 cd ..。如果 PROMETHEUS 未定义(脚本未定义它,则变为 cd /sources/ 也应该失败但不会中止您的脚本。尝试

cd $PROMETHEUS/sources/ || exit 1

相反。 #!/bin/bash -u 也可能有用(在未定义的变量上中止)。

最后,您可以使用 pushdpopd 浏览文件夹。