Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write stdout to file with colors?

A lot of times (not always) the stdout is displayed in colors. Normally I keep every output log in a different file too. Naturally in the file, the colors are not displayed anymore.

Console color output example

I'd like to know if there's a way (in Linux) to write the output to a file with colors. I'm trying to use tee to write the output of vagrant to a file, this way I can still see the output (when it applies). I want to use it specifically for vagrant (it may change in the future, of course...)

like image 721
AAlvz Avatar asked Dec 10 '14 09:12

AAlvz


People also ask

How can you preserve colors in stdout while piping to tee?

Simply insert unbuffer before any command to make it think it is writing to an interactive output even if it is actually piping into another executable. This will preserve color in the case of ls .

How do I output colored text to a Linux terminal?

A script can use escape sequences to produce colored text on the terminal. Colors for text are represented by color codes, including, reset = 0, black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, and white = 37.


3 Answers

Since many programs will only output color sequences if their stdout is a terminal, a general solution to this problem requires tricking them into believing that the pipe they write to is a terminal. This is possible with the script command from bsdutils:

script -q -c "vagrant up" filename.txt 

This will write the output from vagrant up to filename.txt (and the terminal). If echoing is not desirable,

script -q -c "vagrant up" filename > /dev/null 

will write it only to the file.

like image 63
Wintermute Avatar answered Sep 19 '22 18:09

Wintermute


You can save the ANSI sequences that colourise your output to a file:

echo a | grep --color=always . > colour.txt
cat colour.txt

Some programs, though, tend not to use them if their output doesn't go to the terminal (that's why I had to use --color-always with grep).

like image 27
choroba Avatar answered Sep 23 '22 18:09

choroba


You can also color your output with echo with different colours and save the coloured output in file. Example

echo -e '\E[37;44m'"Hello World" > my_file

Also You would have to be acquainted with the terminal colour codes

Using tee

< command line > |tee -a 'my_colour_file'

Open your file in cat

cat 'my_colour_file'

Using a named pipe can also work to redirect all output from the pipe with colors to another file

for example

Create a named pipe

mkfifo pipe.fifo

each command line redirect it to the pipe as follows

<command line> > pipe.fifo

In another terminal redirect all messages from the pipe to your file

cat pipe.fifo > 'my_log_file_with_colours'

open your file with cat and see the expected results.

like image 39
repzero Avatar answered Sep 21 '22 18:09

repzero