Thanos
Thanos

Reputation: 711

redirect all output in a bash script when using set -x

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.

Upvotes: 46

Views: 53502

Answers (4)

calamari
calamari

Reputation: 367

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.

Upvotes: 3

PALEN
PALEN

Reputation: 2886

To redirect stderr and stdout:

exec &>> $LOG_FILE_NAME

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

exec &> $LOG_FILE_NAME

Upvotes: 3

bcelary
bcelary

Reputation: 1837

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.

Upvotes: 64

Anya Shenanigans
Anya Shenanigans

Reputation: 94869

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

set -x
exec 2>/tmp/mylog

Upvotes: 19

Related Questions