Brandt
Brandt

Reputation: 5639

In a shell script: redirect echo shell commands as they are executed

This is an extension to the question In a shell script: echo shell commands as they are executed.

So we have our command line echo'd either by using set -v (for verbose, before expansions), or set -x (for xtrace, after expansions); or both set -vx. Great.

My question is: how do we redirect those echo'd lines (to a file, for instance)?

If I run the following lines,

BLA='xyz'
set -v
echo $BLA > bla.log

, clearly, bla.log will contain 'xyz', not the echo 'echo $BLA > bla.log'.

I clearly need a better/depper understanding about the shell to see what is going on here; would appreciate very much a deeper explanation besides the 'howto redirect' solution.

Thanks

Upvotes: 0

Views: 578

Answers (2)

ilkkachu
ilkkachu

Reputation: 6517

To send the xtrace output to somewhere else than stderr, you can set BASH_XTRACEFD to the number of an open file descriptor. E.g. this would direct the xtrace output to a file called xtrace:

$ exec 19>xtrace; BASH_XTRACEFD=19; set -x

(I pulled 19 out of a hat, you could use any fd number, provided it's not used to do something else)

Upvotes: 2

William Pursell
William Pursell

Reputation: 212218

The text printed as a result of set -x and set -v is being written to stderr. If you want all output to go to bla.log, just do:

exec > bla.log 2>&1
set -v 
echo bla 

Upvotes: 1

Related Questions