How to write stdout to file with colors?

AAlvz picture AAlvz · Dec 10, 2014 · Viewed 23.6k times · Source

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...)

Answer

Wintermute picture Wintermute · Dec 10, 2014

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.