【问题标题】:Redirect set -x / set -o xtrace to standard output重定向 set -x / set -o xtrace 到标准输出
【发布时间】:2021-06-23 04:36:49
【问题描述】:

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

【问题讨论】:

    标签: bash stdout stderr


    【解决方案1】:

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

    【讨论】:

    • 这似乎将命令输出到 /tmp 中的文件。要回答 OP 的问题,请在 set +x 之前添加export BASH_XTRACEFD=1,它将打印到标准输出
    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2017-07-06
    • 2013-02-28
    • 1970-01-01
    • 2014-01-20
    相关资源
    最近更新 更多