49

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!

Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
Zack Xu
  • 11,505
  • 9
  • 70
  • 78
  • 1
    http://superuser.com/q/124846/105002 – choroba Nov 08 '12 at 17:26
  • grep --color=always pattern file[or]string | less -R – Saeed Zahedian Abroodi Apr 12 '20 at 11:00
  • 1
    [How to trick an application into thinking its stdout is a terminal, not a pipe](https://stackoverflow.com/questions/1401002/how-to-trick-an-application-into-thinking-its-stdout-is-a-terminal-not-a-pipe) – bain May 27 '20 at 10:04
  • Also [Can colorized output be captured via shell redirect?](https://stackoverflow.com/questions/3515208/can-colorized-output-be-captured-via-shell-redirect) – bain May 27 '20 at 10:05

2 Answers2

51

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.

user986730
  • 1,226
  • 1
  • 13
  • 12
  • 2
    And for `git status`, it is [`git -c color.status=always status | less -REX`](https://stackoverflow.com/a/18304605/1048186) – Josiah Yoder May 26 '20 at 14:41
  • thank you. I had found the answer to this years ago but obviously did not read enough. I had it in my mind that -R flag for less was the solution. After changing jobs, I found it wasn't working anymore and never bothered to look into it until now. Thanks for explaining you need to use the output colour on the preceeding command before less as well as using the -R flag for less! – Arthur Bowers Jul 08 '22 at 10:42
22

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820