Piping the output of ls or tree to less loses colors

lessls

tree and ls can distinct file types by coloring filenames differently.

tree and ls often output a long list of files (including directories), so I pipe the stdout output to less.

But less doesn't preserve the colors. How can we make it show colors, or some alternative ways?

Just saw the linked list, but piping to less -R or less -r doesn't work. My OS is Ubuntu 12.04. less is Version 444: 09 Jun 2011.

Best Answer

I'm going to assume you're using ls --color=auto, which tells ls to use color in 'automatic' mode. 'Automatic' mode tells less to see if STDOUT is a terminal, and if so, use color, otherwise don't use color. When you pipe ls into less, STDOUT is not a terminal, it's connected to STDIN of less, which is a normal pipe.

The solution, use ls --color or ls --color=always.

However now this leads to another potential issue. Depending on your less, it may not show the color, but show the escape codes instead. The solution is to use less -R. This tells less to pass through the escape codes for ANSI color escapes. You don't want to use -r as this will cause problems with long lines that wrap around, as less doesn't properly calculate line length.

So full solution:

ls --color | less -R

Similarly for tree:

tree -C | less -R