128

When I have dircolors defined life is full of... color.

When I pipe ls through less to scroll around I lose the colors.

Any suggestions?

2 Answers 2

123

Most likely your ls is aliased to ls --color=auto, which tells ls to only use colors when its output is a tty. If you do ls --color (which is morally equivalent to ls --color=always), that will force it to turn on colors.

You could also change your alias to do that, but I wouldn't really call that a good idea. Better to make a different alias with --color.

less needs -R too, which causes it to output the raw control characters.

2
  • 5
    Why would you not call it a good idea to alias ls to ls --color or ls --color=always, for that matter?
    – j08lue
    Apr 8, 2015 at 13:38
  • 12
    @j08lue if you pipe through a command that doesn't handle color, you get some junk characters that may mess up the command. For example, I did ls --color=always | less and got: ESC[01;32mexecute_once.shESC[0m (I know this is old and you probably don't care, but for future visitors, this may be useful)
    – Ryan Amos
    Jun 30, 2015 at 16:51
65

Try less with the -R option like this:

command | less -R

This works for me in a one-liner like this:

ls -la | grep --color=always bash | less -r

And like this too:

ls --color | less -R

But you have to tweak the primary output (the output of ls in this case) a bit with the --color parameter.

6
  • Thanks, this also works for ack-grep. ack-grep my_string --color | less -R
    – igniteflow
    Jan 30, 2014 at 14:25
  • 1
    --color is not recognized: ls: illegal option -- - Running bash on osx.
    – SMBiggs
    Oct 17, 2014 at 17:04
  • 1
    @Scott Biggs: in OSX there is no --color; try ls -G
    – user262186
    Jan 3, 2015 at 6:34
  • @Lu-Chi, Even with -G, the colors are missing Feb 6, 2015 at 10:26
  • 3
    The -R option is short for --RAW-CONTROL-CHARS. Mar 28, 2018 at 21:15

You must log in to answer this question.

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