Preserving color of text piped through "less" or "more"

Certain commands produce text in color for readability.

I'm using Linux. For example when I'm using rak or hg diff the output is in color for better readability.

However when I pipe the output through less

hg diff | less

the colors are lost.

How do I preserve the color?

Thanks!


Solution 1:

I believe some commands are smart enough NOT to output color if they detect that they are writing to a pipe or a file instead of to the console, since that could ruin the parsing of their output by the next program in the pipeline.

You can try forcing the programs into outputting color with their respective flags (e.g. --color or whatever), but it's ultimately implementation dependent if they'll honor your request or not.

GNU grep 2.27, for example, will not output color into less even when passing --color to it. But if you pass --color=always and pipe it into less, you'll be able to see the color escape codes through less. And then, using the -R flag will have less interpret the color escape codes.

Solution 2:

Try less -r or (safer) less -R. See the manual.

Since you probably don't want to specify that all the time:

export LESS=-R # Put that in a startup script like .bashrc.local
hg diff | less

For Mercurial, you can also use the pager extension.