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

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


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/bashlogfile=$$.logexec > $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.


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

set -xexec 2>/tmp/mylog


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>&1set -x

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