19

Using set -x in bash prints the shell-expanded commands to stderr. I would like to redirect these to a file or pipe. But not the whole output - only some commands. Something like:

set -x command.txt  ### <-- command.txt param is made up
echo $A $B
set +x

This would put the debug output to command. txt.

Can this be done?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
  • Found this, http://stackoverflow.com/questions/3173131/redirect-copy-of-stdout-to-log-file-from-within-bash-script-itself , only works for stdout. – Ondra Žižka Aug 31 '14 at 15:36

1 Answers1

23

With bash 4.1 or later:

#!/bin/bash

exec 5> command.txt
BASH_XTRACEFD="5"

echo -n "hello "

set -x
echo -n world
set +x

echo "!"

Output to stdout (FD 1):

hello world!

Output to command.txt (FD 5):

+ echo -n world
+ set +x
chepner
  • 497,756
  • 71
  • 530
  • 681
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • like any good logger, each line should have a timestamp. is there a way to get a timestamp using this method of creating a file descriptor `5`, and log the current time of the line being executed? – activedecay Feb 26 '19 at 21:44
  • 2
    @activedecay: *If you have access to logger command then you can use [this](https://unix.stackexchange.com/a/155553/74329) to write debug output via your syslog with timestamp, script name and line number.* – Cyrus Feb 27 '19 at 05:09