If I run
ls I get colored output which I find pretty handy for quickly getting a glance of the kind of file. When I try to pipe it to
less even with the
-R flags the coloring always get lost. I am using
zsh version 5.0.7. Any ideas? Thanks.
edit: I am on OS X.
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
This is by design: programs that produce colored output typically do so only when their output goes to a terminal, not when it’s sent to a pipe or to a regular file. The reason is that data sent on a terminal is presumably read by a human, whereas data piped to a program or written to a file is likely to be parsed by some program, so it shouldn’t contain extraneous content like color-changing escape sequences.
ls displays colored output on a terminal when you pass the option
--color=auto). To force colored output regardless of the file type of the standard output, pass
--color=yes (they’re synonyms). This convention has been followed by other commands, like GNU grep, FreeBSD grep,
git diff, etc.
ls --colors=yes -l | less
With the FreeBSD version of
ls(also found on OSX, and available as the
colorlsport on OpenBSD and NetBSD), pass the option
-Gto display colors when the output is a terminal. Set the environment
CLICOLOR_FORCEto display colors regardless of the output file type.
CLICOLOR_FORCE=1 ls -l | less
The problem most probably is that your
ls program has set option
--color=auto which basically means that output should be coloured only if it is connected to terminal, otherwise (output connected to a pipe or a file) no colors are emitted.
If you want to have colors is such cases you should set
--color option to
always, so try
ls --color=always | less -R
If this behaviour is what you expect all the time then just create alias:
alias ls='ls --color=always'
I can’t comment @jimmij ‘s answer, because I have less than 50 rep, but I would like to explain what worked for me in Bash.
If you run
$ man ls | grep color
you will see all the entries of the
man-page for your specific shell environment (in our case
For me the following adjustment did the trick:
$ alias ls='ls -G'