Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 667
Thanos Avatar asked Jun 27 '12 15:06

Thanos


People also ask

How do you redirect all output from a shell script to a file?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.

How do I redirect all output to a file in Linux?

As redirection is a method of capturing a program output and sending it as an input to another command or file. The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

How do I redirect an output?

The > symbol is used to redirect output by taking the output from the command on the left and passing as input to the file on the right.

What does &> mean in bash?

&>word (and >&word redirects both stdout and stderr to the result of the expansion of word. In the cases above that is the file 1 . 2>&1 redirects stderr (fd 2) to the current value of stdout (fd 1).


3 Answers

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.

like image 106
bcelary Avatar answered Sep 18 '22 21:09

bcelary


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

set -x exec 2>/tmp/mylog 
like image 37
Petesh Avatar answered Sep 17 '22 21:09

Petesh


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.

like image 30
calamari Avatar answered Sep 21 '22 21:09

calamari