5

I have a bash script and I want to capture a portion of the script with a set -x and redirect that output to a file.

I can see what the ENVFILE is setting but its going to std out.

Is there a way I can capture the output of the set -x into a file instead of std out ?

#!/bin/sh
...a bunch of stuff....

if [ -e ${ENVFILE} ]; then
set -x
. ${ENVFILE}
set +x
fi # ! -e PROJOB
... a bunch of stuff .... 
0

2 Answers 2

6

If you're using bash, you can use BASH_XTRACEFD:

...
if [ -e ${ENVFILE} ]; then
  BASH_XTRACEFD=3
  set -x
  . ${ENVFILE}
  set +x
  unset BASH_XTRACEFD
fi # ! -e PROJOB
...

Then execute the script like so:

/path/to/script 3>/path/to/trace.output

Use a file descriptor other than 3 if you're already using FD 3.

1
  • Thank You !... This BASH_XTRACEFD command is pretty cool ! Oct 7, 2016 at 19:51
0

I'd do it this way. Look at the comments in the code.

#!/bin/sh
...a bunch of stuff....

if [ -e ${ENVFILE} ]; then

#save the file descriptor of the current stderr
exec 3>&2
#redirect to the file
exec 2>/.../you_file

set -x
. ${ENVFILE}
set +x

#restore original redirection
exec 2>&3
#close file descriptor 3
exec 3>&-

fi # ! -e PROJOB
... a bunch of stuff .... 

If you want the standard output redirected beside the debugging stuff, you need to redirect the file descriptor 1 in a similar way to fd 2 using exec.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .