首页 > 解决方案 > 重定向 set -x / set -o xtrace 到标准输出

问题描述

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

标签: bashstdoutstderr

解决方案


您可以使用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

推荐阅读