How do I keep color output when paginating shell output through less?

Let’s say that you like the color output that comes out of ls (different colors for different file types). But when you have lots of files and want to paginate it through less, you lose the color output. So how do we keep the colors?

You need to give the -r flag to less to tell it to pass through the color escape sequences:


ls | less -r

That might not work because on some systems ls is set as an alias to:


ls —color=auto

(you can find out by typing “alias ls”)

That makes it show color only for interactive terminals (sort of…) but piping
into less isn’t an interactive terminal.

So you can do this:


ls —color | less -r

or

ls —color=always | less -r

That’s probably too much trouble, so you can set up an alias by
editing your ~/.bash_profile and adding this: (if you’re using bash as your shell)


alias lsl=‘ls —color=always | less -r’

You can change lsl to whatever name you like.

Or if you want a long directory listing, you can do something like this:


alias lsl=‘ls -alg —color=always | less -r’