Piping ls through less with colors

Date: 20 Oct, 2008
Posted by: admin
In: hints & tips|linux, open source & software

Bookmark and Share

piping \Here’s one you may have pondered, can you pipe ls through less and keep the colours? Well, yes, yes you can and you can even set it up to work just by typing “ls”.

Well the answer is in the man pages, from “man ls”:

By default, color is not used to distinguish types of files. That is equivalent to using --color=none. Using the --color option without the optional WHEN argument is equivalent to using --color=always. With --color=auto, color codes are output only if standard output is connected to a terminal (tty). The environment variable LS_COLORS can influence the colors, and can be set easily by the dircolors command.

My emphasis above shows why ls won’t pipe through less properly and keep the colors. Now I had an alias in my ~/.bashrc file:

lh='ls --color=auto -lasth | less -R'

This at first glance looks like it pipes ls through less and keeps the colour codes (see man less for what the -R switch does). It does, only ls doesn’t send the colour codes because it doesn’t think it’s being output to a TTY (see quoted man above). So all you need to do is ensure that --color=always is set (--color=yes appears to work too but may not be POSIX compliant). HTH, happy bash-ing!

2 Responses to "Piping ls through less with colors"

Andreas Roussos says:

Brilliant tip, cheers!

admin says:

No worries Andreas thanks for stopping by.

I actually most often use ll, for which I have

alias ll=’ls –color=yes -lshF | less -R’

in my .bashrc. Thing is I’m actually a bit annoyed with the pager (less) part now having used this for a while. I actually find it easier to just scroll back in the terminal as I rarely bother searching in less. FWIW.


About

Flapjacktastic is just a random collection of musings, hints&tips, notes, information ... a collection of stuff really that's overflowed from the brain of this husband, father, potter, business-man, geek ...

past posts