How to write stdout to file with colors? How to write stdout to file with colors? bash bash

How to write stdout to file with colors?


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.


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

echo a | grep --color=always . > colour.txtcat 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).


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.