balkon16
balkon16

Reputation: 1438

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

I'm using set -x (also known as set -o xtrace) to log the commands and their arguments in my script that are executed. I find it problematic that the commands and their arguments are redirected to stderr. I need the stderr channel to store only real errors that's why using ./script.sh --arg ${ARG} 2>1 is not a solution. Is there a way to redirect to stdout commands and their arguments generated by the set -x command?

Upvotes: 6

Views: 1509

Answers (1)

P.P
P.P

Reputation: 121397

You can use BASH_XTRACEFD to redirect the trace output.

 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.

Something like:

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

Upvotes: 8

Related Questions