Why does grep not show colors despite –color=always

colorsgrepregular expression

Works:

echo '\example' | grep --color=always -i '.example'

Works:

echo '\example' | grep --color=always -i '\\example'

Matches, but missing colors:

echo '\example' | grep --color=always -i '\example'

Best Answer

Finding the discrepancy

I spent some time poking through the source code for grep and narrowed down the problem a bit.

The main issue lies in the function print_line_middle. See this loop construct:

for (cur = beg;
     (cur < lim && ((match_offset = execute (compiled_pattern, beg, lim - beg,
                                             &match_size, cur)) != (size_t) -1));
     cur = b + match_size)
{

The discrepancy

The issue is that for example #3 above, the match_offset = execute(...) call is equal to -1. This result influences when the printing is done and thereby what colors are used.

Is this a bug?

I have no idea :) but feel free to send the devs an email. From the README:

Send bug reports to bug-grep@gnu.org.

Related Question