When I run a program (for example grep
or ls
) without a pager, its output is colored. However when I run it piping its output to less
, no colors are shown.
For example, this command outputs colored output:
grep -r something
but this doesn't:
grep -r something | less
Why? How can I see colors through less
?
There are two problems here:
ls
—which auto-detect the colour support— don't find support from pipesless
is set to just display colour codes by default.Both can be overcome but it's a bit clunky:
This isn't
ls
specific. Many commands that support colour also have an override argument.A slightly more in-depth answer is that
ls
is checking whether or not its STDOUT belongs to a real terminal or not. When you pipe things around, the STDOUT is set to the STDIN of the next command.You can see this at work in the
ls
source code. It's using theisatty
command (a core POSIX interface) to work out what the situation is:Are colours on by default:
Do we try to output in multiple columns:
grep
does a very similar thing, unless explicitly overridden, it'll detect colour support, withisatty
:If you're interested in colors in
less
more generally, you might want to look atlesspipe.sh
. See, for example, https://github.com/wofr06/lesspipe.It will also colorize shell scripts, perl scripts, etc. similarly to a text editor, but without the use of any "preprocessing" program to do the colorizing.