souser
souser

Reputation: 6120

bash direct output to log file in addition to stdout

I am trying to log the changes made by my script to a log file. At a very high level, my script has functions and I want to be able to log that information to a file. I used "tee -a" but that messed up the functionality in a number of ways.

Is there a simple way to achieve this task ?

Update : Corrected typo below

function1(){ ... }
function2(){ ... }
#main
function1 | tee -a /tmp/logfile
function2 | tee -a /tmp/logfile

Upvotes: 0

Views: 186

Answers (1)

William Pursell
William Pursell

Reputation: 212248

(edited to reflect question edits) You can incorporate the tee into the function definition:

function() { { ...<original function definition goes here>; } | tee -a output; }

so you don't need to invoke tee each time you call the function. Obviously, if the function modifies file descriptors, you will need to do a little more work. Also, keep in mind that this changes the buffering. If commands called from within function1 have a tty for their stdout, they will probably line buffer their output, but if their stdout is a pipe (which it is if you are piping to tee) the output will be block buffered. This may be the root cause of the differences you are seeing. Also, this only captures the output of one file descriptor. Perhaps you have commands writing to stderr. You will need to provide more details about the way the pipe to tee changes the behavior of the script.

Upvotes: 1

Related Questions