如何使“bash -x”(调试模式)递归到源脚本中?

Kel*_*vin 10 linux bash macos

我正在尝试调试 bash 在 Linux 登录初始化时所做的事情。我读过“bash -x”将使 bash 打印出它在做什么,但它不会像“set -x”那样打印源文件中的命令。我不能使用“set -x”,因为初始化在我调用它之前运行。“bash -x”似乎在 OS X 上递归得很好,但这可能是因为 bash 版本。

Linux:3.2.25

OS X:3.2.48

以下是 Linux 上非递归行为的摘录:

bash -l -x -c 'echo 1'
# ... snip ...
+ for i in '/etc/profile.d/*.sh'
+ '[' -r /etc/profile.d/vim.sh ']'
+ '[' '' ']'
+ . /etc/profile.d/vim.sh
+ for i in '/etc/profile.d/*.sh'
+ '[' -r /etc/profile.d/which-2.sh ']'
+ '[' '' ']'
+ . /etc/profile.d/which-2.sh
# ... snip ...
Run Code Online (Sandbox Code Playgroud)

注意 /etc/profile.d/vim.sh 的来源,但它的命令没有打印出来。有没有不升级的解决方法?这是版本差异导致的吗?

mka*_*ito 1

set -x根文件中的某处(需要所有其他文件的文件)应该可以工作。或者,[[ !-z "$DEBUG" ]] && set -x在每个文件中引入类似的内容,然后使用DEBUG=1 script.sh.

  • 请思想更加开放一些——显然 bash 的创建者认为它会很有用。我看到(至少)有 2 个用途:1)你想运行 `ssh user@host 'bash -l -c command'` 这样你就可以加载正确的环境。2) 您是系统管理员,想要在脚本运行之前*排除*初始化脚本正在执行的操作 - `bash -l -x` 将向您显示。有时您想知道环境变量的设置位置。 (3认同)