[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
bug#20837: Code for --color=auto
From: |
Eric Blake |
Subject: |
bug#20837: Code for --color=auto |
Date: |
Wed, 17 Jun 2015 13:52:39 -0600 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.7.0 |
On 06/17/2015 08:08 AM, Paul J. Lucas wrote:
> Hello -
>
> I have my own C program where I also use SGR to produce color just like grep
> does. I pulled the grep source (2.21) to see how —color=auto was
> implemented. In grep.c, lines 2440-2441, there is the code:
>
> if (color_option == 2)
> color_option = isatty (STDOUT_FILENO) && should_colorize ();
>
> The thing about using isatty() is that it doesn’t work for the common case of
> piping the output of grep to less. What about using fstat(STDOUT_FILENO)
> instead? From testing (where “C” is an C program that outputs color using
> SGR), I’ve gotten:
But you don't always want color when piping. For example, if you run a
chain of commands 'grep | grep', if the first grep adds color, the
second grep will NOT be grepping the original input, but the altered
colorized output.
>
> COMMAND Should? isatty ISCHR ISFIFO ISREG
> ======== ======= ====== ===== ====== =====
> C T T T F F
> C > file F F F F >>T<<---- The interesting case.
> C | less T F F T F
>
> Hence, it would seem that we want to output color except when ISREG on the
> stat struct on stdout is T. Wouldn’t this make better logic for —color=auto ?
No, we want --color=auto to be tied SPECIFICALLY to a tty, and if you
want color to a pipe, you should use --color=always rather than
--color=auto. This is true not only for grep --color, but also for
coreutils' ls --color, and any other program that supports --color.
[Side discussion - I wish we could have consistency in GNU projects
about whether plain --color is shorthand for --color=auto or
--color=always; different programs have picked different defaults, but
both sides have an argument for their choice and an issue with potential
back-compat breakage to clients if they change the default]
--
Eric Blake eblake redhat com +1-919-301-3266
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature