将 set -x / set -o xtrace 重定向到标准输出

Redirect set -x / set -o xtrace to standard output

我正在使用 set -x(也称为 set -o xtrace)来记录我的脚本中执行的命令及其参数。我发现命令及其参数被重定向到 stderr 是有问题的。我需要 stderr 通道只存储真正的错误,这就是为什么使用 ./script.sh --arg ${ARG} 2>1 不是解决方案。有没有办法重定向到 stdout 命令及其由 set -x 命令生成的参数?

您可以使用 BASH_XTRACEFD 重定向跟踪输出。

 BASH_XTRACEFD
          If set to an integer corresponding to a valid file
          descriptor, bash will write the trace output generated
          when set -x is enabled to that file descriptor.  The file
          descriptor is closed when BASH_XTRACEFD is unset or
          assigned a new value.  Unsetting BASH_XTRACEFD or
          assigning it the empty string causes the trace output to
          be sent to the standard error.  Note that setting
          BASH_XTRACEFD to 2 (the standard error file descriptor)
          and then unsetting it will result in the standard error
          being closed.

类似于:

#!/bin/bash
exec 10> /tmp/xtrace
export BASH_XTRACEFD=10
...
# rest of the script