Windows – What does the grep switch –color=auto do

command linegnuwin32grepwindows

What effect does auto as an option for the --color switch have in grep? When does grep decide to color the the matching strings, and when doesn't it?

Best Answer

Expected behavior

With --color=auto, grep will highlight matching strings if (and only if) the output is written directly to the terminal and said terminal is capable of displaying colored output.

Normally, --color=auto is what you want. If, e.g., you use grep to match a URL and pipe it to Wget, Wget will see \e[1;31mhttp://... instead of the actual URL (and choke on it).

The following commands should result in colored output:

echo Super User | grep --color=auto Super
echo Super User | grep --color=always Super | cat

This command, however, should not:

echo Super User | grep --color=auto Super | cat

Any inconsistency with this behavior should be considered a bug.

Source code

With --color=auto, the latest Grep for Windows version (2.5.4) – as well as the original 2.5.4 it is based on – color the output if and only if the condition

isatty(STDOUT_FILENO) && getenv("TERM") && strcmp(getenv("TERM"), "dumb")

is true, i.e., if and only if the output is being written to a terminal, the environment variable TERM is defined and the terminal is not dumb.

This won't produce the desired behavior under Windows, since TERM is normally not defined. An easy solution to this problem is setting the TERM=windows in the control panel.

The latest version of grep (2.14) fixes this issue by coloring the output if and only if the condition

isatty(STDOUT_FILENO) && should_colorize()

is true, where should_colorize() is defined differently for POSIX and Win32:

For the former, the condition is equivalent to the one of 2.5.4; for the latter, the enviroment variable TERM doesn't have to be set (it just can't be dumb).

Related Question