15

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.

6
  • 1
    @JosephR. the other question is half-related but not a duplicate. Here we're talking ls (not tree) for which some implementations need to be told to force color output when the output doesn't go to a terminal (in addition to less -R being needed) Jul 29, 2014 at 13:45
  • Have you tried tree -C | less -R? The -C option is tree's equivalent of less's --color=always, I think (at least it works for me, on Ubuntu 12.04). Jul 29, 2014 at 13:51
  • @steeldriver thanks. it works. tree with and without -C alone always output in colors, but why are they different when used with less?
    – Tim
    Jul 29, 2014 at 13:57
  • @Tim 2 reasons: 1. less removes the colors by default unless you give it the -R option, which tells it to leave it in, and 2. tree and ls and other programs usually turn coloring off when they detect their output is going to another program (like less) instead of directly to your terminal, unless you force the coloring on with -C or --color=always.
    – jw013
    Jul 29, 2014 at 14:42
  • 2
    What is this linked list you write about?
    – Anthon
    Jul 29, 2014 at 14:44

1 Answer 1

19

I'm going to assume you're using ls --color=auto, which tells ls to use color in 'automatic' mode. 'Automatic' mode tells ls 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .