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
).
Simply add the following alias to your shell's configuration file, e.g. .bashrc
or .bash_profile
(depending on which you use, see here):
alias grep='grep --color=auto'
You can simply use it as grep
.
There's usually no need to make scripts when simple command aliases do the same thing just fine. In fact your script wouldn't even work if you wanted to pass more options to grep
. In case you need a tiny snippet that can deal with arguments, you should use functions.
Best Answer
From
man grep
on my computer: