44

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.

Thanos
  • 691
  • 1
  • 5
  • 14
  • 1
    See [this question](http://stackoverflow.com/questions/692000/how-do-i-write-stderr-to-a-file-while-using-tee-with-a-pipe). It's not a duplicate, but I believe this should answer your question. – vergenzt Jun 27 '12 at 15:26

4 Answers4

63

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.

Community
  • 1
  • 1
bcelary
  • 1,827
  • 1
  • 17
  • 17
  • 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? – Joey T Feb 19 '13 at 02:46
  • 2
    @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](http://tldp.org/LDP/abs/html/ioredirintro.html) – nik Feb 14 '14 at 06:40
  • @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. – Adam Spiers Sep 13 '16 at 15:25
17

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

set -x
exec 2>/tmp/mylog
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
3

To redirect stderr and stdout:

exec &>> $LOG_FILE_NAME

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

exec &> $LOG_FILE_NAME
PALEN
  • 2,784
  • 2
  • 23
  • 24
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.

calamari
  • 329
  • 2
  • 8