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?
Windows – What does the grep switch –color=auto do
command linegnuwin32grepwindows
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:
This command, however, should not:
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 conditionis 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 theTERM=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
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 bedumb
).