Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

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!

like image 788
Zack Xu Avatar asked Nov 08 '12 17:11

Zack Xu


2 Answers

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.

like image 73
user986730 Avatar answered Oct 22 '22 16:10

user986730


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.

Note: Some commands automatically turn of color output when they detect the output goes to a pipe instead of the terminal. To fix this, force color output.

For example ls -al will show color output but ls -al | less -R will not. ls -al --color | less -R will work as expected.

like image 22
Aaron Digulla Avatar answered Oct 22 '22 17:10

Aaron Digulla