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?

1

1 Answer 1

22

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
2
  • 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? Feb 26, 2019 at 21:44
  • 2
    @activedecay: If you have access to logger command then you can use this to write debug output via your syslog with timestamp, script name and line number.
    – Cyrus
    Feb 27, 2019 at 5:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.