如何判断当前正在执行的 bash 脚本是否已使用 -x 调用以进行调试?

Dan*_*scu 11 bash debugging

我有一个脚本launch.sh,它作为另一个用户执行,以便创建具有正确所有者的文件。如果最初传递给脚本,我想将 -x 传递给此调用

if [ `whoami` == "deployuser" ]; then
  ... bunch of commands that need files to be created as deployuser
else
  echo "Respawning myself as the deployment user... #Inception"
  echo "Called with: <$BASH_ARGV>, <$BASH_EXECUTION_STRING>, <$->"
  sudo -u deployuser -H bash $0 "$@"  # How to pass -x here if it was passed to the script initially?
fi
Run Code Online (Sandbox Code Playgroud)

我已经阅读了bash 调试页面,但似乎没有明确的选项可以说明原始脚本是否使用-x.

phe*_*mer 16

许多可以bash在命令行上传递的标志都是set标志。set是内置的 shell,它可以在运行时切换这些标志。例如,调用脚本 as与在脚本顶部bash -x foo.sh执行基本相同set -x

知道这set是负责这个的内置 shell 让我们知道去哪里找。现在我们可以做help set,我们得到以下内容:

$ help set
set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
...
      -x  Print commands and their arguments as they are executed.
...
    Using + rather than - causes these flags to be turned off.  The
    flags can also be used upon invocation of the shell.  The current
    set of flags may be found in $-.  The remaining n ARGs are positional
    parameters and are assigned, in order, to $1, $2, .. $n.  If no
    ARGs are given, all shell variables are printed.
...
Run Code Online (Sandbox Code Playgroud)

所以从这里我们看到$-应该告诉我们启用了哪些标志。

$ bash -c 'echo $-'
hBc

$ bash -x -c 'echo $-'
+ echo hxBc
hxBc
Run Code Online (Sandbox Code Playgroud)

所以基本上你只需要做:

if [[ "$-" = *"x"* ]]; then
  echo '`-x` is set'
else
  echo '`-x` is not set'
fi
Run Code Online (Sandbox Code Playgroud)

作为奖励,如果你想复制所有的标志,你也可以这样做

bash -$- /other/script.sh
Run Code Online (Sandbox Code Playgroud)


Pau*_*bro 1

您可以获取进程的 PID,然后使用 ps 检查进程表以查看其参数是什么。

  • 我认为这通常不是一个好主意,因为如果在脚本内设置了“-x”,它将不会显示在“ps”输出中。而且这个解决方案无论如何都是低效的。 (2认同)