47

I have a bash script that has set -x in it. Is it possible to redirect the debug prints of this script and all its output to a file? Ideally I would like to do something like this:

#!/bin/bash
set -x
(some magic command here...) > /tmp/mylog
echo "test"

and get the

+ echo test
test

output in /tmp/mylog, not in stdout.

1
  • 1
    See this question. It's not a duplicate, but I believe this should answer your question. Commented Jun 27, 2012 at 15:26

4 Answers 4

64

This is what I've just googled and I remember myself using this some time ago...

Use exec to redirect both standard output and standard error of all commands in a script:

#!/bin/bash
logfile=$$.log
exec > $logfile 2>&1

For more redirection magic check out Advanced Bash Scripting Guide - I/O Redirection.

If you also want to see the output and debug on the terminal in addition to in the log file, see redirect COPY of stdout to log file from within bash script itself.

If you want to handle the destination of the set -x trace output independently of normal STDOUT and STDERR, see bash storing the output of set -x to log file.

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. How could I use this method to both capture errors (stdout 2) into a logfile AND return them to stdout 2; so cron could properly email error alerts?
@JoeyT, see if this works for you: backup the STDOUT before setting up logfile with exec 3<&1, then add in these two lines at the end: exec 1<&3 3<&- and cat $$.log -- this should restore STDOUT and close fd 3 to cleanup. Based on the original tldp reference and this http://tldp.org/LDP/abs/html/ioredirintro.html
@JoeyT I've edited the answer and added two more helpful links; the first one should be enough to explain how you can do this.
19

the -x output goes to stderr, so to log it do:

set -x
exec 2>/tmp/mylog

Comments

3

To redirect stderr and stdout:

exec &>> $LOG_FILE_NAME

If you want to append to file. To overwrite file:

exec &> $LOG_FILE_NAME

Comments

3

In my case, the script was being called multiple times from elsewhere, and I wasn't seeing everything, so I did an append instead, and it worked:

exec 1>>FILENAME 2>&1
set -x

To avoid confusion, be sure to delete FILENAME before each run.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.