Command-line Knowledge Base

Redirection and colourized output

Preserve colors while piping to tee [1]

Use the ls option --color=always

--color=auto will not color output to a pipeline - for obvious reasons.

The ls man page says the following:

With --color=auto, color codes are output only if standard output is connected to a terminal (tty).
Can colorized output be captured via shell redirect? [2]

Redirecting doesn't strip colors, but many commands will detect when they are sending output to a terminal, and will not produce colors by default if not. For example, on Linux ls --color=auto (which is aliased to plain ls in a lot of places) will not produce color codes if outputting to a pipe or file, but ls --color will. Many other tools have similar override flags to get them to save colorized output to a file, but it's all specific to the individual tool.

Even once you have the color codes in a file, to see them you need to use a tool that leaves them intact. less has a -r flag to show file data in "raw" mode; this displays color codes. edit: Slightly newer versions also have a -R flag which is specifically aware of color codes and displays them properly, with better support for things like line wrapping/trimming than raw mode because less can tell which things are control codes and which are actually characters going to the screen.