Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect COPY of stdout to log file from within bash script itself

I know how to redirect stdout to a file:

exec > foo.log echo test 

this will put the 'test' into the foo.log file.

Now I want to redirect the output into the log file AND keep it on stdout

i.e. it can be done trivially from outside the script:

script | tee foo.log 

but I want to do declare it within the script itself

I tried

exec | tee foo.log 

but it didn't work.

like image 938
Vitaly Kushner Avatar asked Jul 03 '10 23:07

Vitaly Kushner


People also ask

How do I redirect a script to log file?

Normally, if you want to run a script and send its output to a logfile, you'd simply use Redirection: myscript >log 2>&1. Or to see the output on the screen and also redirect to a file: myscript 2>&1 | tee log (or better still, run your script within the script(1) command if your system has it).

How do I copy a stdout to a file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do I redirect a output to a file in bash?

For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.

How do I redirect stdout to syslog?

You can redirect any stream in C++ via the rdbuf() command. This is a bit convoluted to implement but not that hard. You need to write a streambuf that would output to syslog on overflow(), and replace the std::cout rdbuf with your streambuf.


1 Answers

#!/usr/bin/env bash  # Redirect stdout ( > ) into a named pipe ( >() ) running "tee" exec > >(tee -i logfile.txt)  # Without this, only stdout would be captured - i.e. your # log file would not contain any error messages. # SEE (and upvote) the answer by Adam Spiers, which keeps STDERR # as a separate stream - I did not want to steal from him by simply # adding his answer to mine. exec 2>&1  echo "foo" echo "bar" >&2 

Note that this is bash, not sh. If you invoke the script with sh myscript.sh, you will get an error along the lines of syntax error near unexpected token '>'.

If you are working with signal traps, you might want to use the tee -i option to avoid disruption of the output if a signal occurs. (Thanks to JamesThomasMoon1979 for the comment.)


Tools that change their output depending on whether they write to a pipe or a terminal (ls using colors and columnized output, for example) will detect the above construct as meaning that they output to a pipe.

There are options to enforce the colorizing / columnizing (e.g. ls -C --color=always). Note that this will result in the color codes being written to the logfile as well, making it less readable.

like image 85
DevSolar Avatar answered Oct 13 '22 08:10

DevSolar