grep results are different when using the –color=always option
I’m having this issue with grep and wondering if it’s a bug. A reproducible scenario is a file that contains the following:
string
string-
and save it as “file”. The goal is to use grep with –color=always to output “string” while excluding “string-“. Without –color, the following will work as expected:
$ grep string file | grep -v string-
But use –color to output two instances:
$ grep --color=always string file | grep -v string-
I tried several variants, but it seems that –-color
breaks the expected behavior. Is this a mistake or am I misunderstanding something? My assumption is that passing --color
should have no effect on the result.
Solution
@Jake Gould’s answer provides a good analysis of what actually happened, but let me try to put it in a different way:
--color=always
Use ANSI escape codes for coloring.
In other words: --color=always
changes its output by design, because it must add the necessary escape sequences to achieve coloring.
Never use –-color=always
unless you know that the output is expected to contain ANSI escape sequences – typically, for the human eyeball on the terminal.
If you’re not sure how the input will be handled, use --color=auto
, which I believe causes grep
to apply shading only when its standard output is connected to the terminal.
In a given pipeline, it usually only makes sense
to apply –color=auto (or –-color=always
) to the grep command, which is the last command in the pipeline.