Brian Chrisman
Brian Chrisman

Reputation: 3684

exporting xtrace/BASH_XTRACEFD but xtrace output going to stderr, not custom filedescriptor

I'm trying to get a shell script executed by a harness to use the harness' BASH_XTRACEFD. Here's a trimmed down version of what I'm attempting that shows the issue. I want '+ echo foobar' in /tmp/xtrace and don't want to reference /tmp/xtrace in /tmp/subject.

[bash]$ cat /tmp/harness
#!/bin/bash
exec 6> /tmp/xtrace
export BASH_XTRACEFD=6
set -o xtrace
export SHELLOPTS
/tmp/subject
set +o xtrace
[bash]$ cat /tmp/subject
#!/bin/bash
echo foobar
echo $SHELLOPTS
echo $BASH_XTRACEFD
ls -l /dev/fd/$BASH_XTRACEFD
[bash]$ /tmp/harness
+ echo foobar
foobar
+ echo braceexpand:hashall:interactive-comments:xtrace
braceexpand:hashall:interactive-comments:xtrace
+ echo 6
6
+ ls -l /dev/fd/6
l-wx------ 1 build build 64 Nov 29 12:15 /dev/fd/6 -> /tmp/xtrace
[bash]$ cat /tmp/xtrace 
+ export SHELLOPTS
+ /tmp/subject
+ set +o xtrace
[bash]$

Upvotes: 2

Views: 1179

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

This appears to be a bug in bash 4.1.x.

From the bash release changelog (in the bash-4.2-alpha section):

ee. Fixed a bug that caused bash to not change the xtrace file descriptor if BASH_XTRACEFD was found in the shell environment at startup.

That said quick testing (with bash 4.1.2) indicates that you can just set BASH_XTRACEFD in the script itself for it to take effect (and it takes effect immediately).

So if you stick BASH_XTRACEFD=$BASH_XTRACEFD at the top of /tmp/subject you'll see its xtrace output in the file the way you want.

Upvotes: 3

Related Questions