Sat, 19 Aug 2006

Paged directory listing with color

A friend had the typical alias ls='ls —color=auto' to produce directory listings in color. When I pipe the output to less, he said, "I lose the colors. For a long listing, I would like to pipe the output to less and preserve the colors. How can I do that?"

With a bit of experimentation, I came up with the following short script and saved it as $HOME/bin/lsl.sh.


 #!/bin/sh
 lsl () {
     /bin/ls --color=always -C $* | less -r
 }

To use it, source it, for example in .bashrc. Then, 'lsl' will behave just like 'ls' except the output will be paged with 'less'. I added the following line to my .bashrc:


 source $HOME/bin/lsl.sh

The trick is to first tell 'ls' to always use color, even when the output is not to a terminal, then tell 'less' to display raw characters with the '-r' option. Because we want to pass arguments to 'lsl' just like we do to 'ls', it needs to be a function, not a simple alias.

[/linux] [link]

About this weblog

This site is the personal weblog of Marc Mims. You can contact Marc by sending e-mail to:
marc@questright.com.

Marc writes here about cycling, programming, Linux, and other items of personal interest.

This site is syndicated with RSS.

Archives

Credits

CSS stolen from Tom Coates who didn't even complain.