On my Ubuntu 20 system, the default coloring when the grep --colors=auto option is used is red text on the normal background. This behavior can be overridden by providing a value to the GREP_COLORS environment variable. For example, export GREP_COLORS='1;37;41' causes grep to display matches in the normal text color on a red background, and thereafter, echo $GREP_COLORS displays the value just set. However, echo $GREP_COLORS is a blank line before the export. Why is this the case? In particular, why does GREP_COLORS appear not to have a default value?
1 Answer
why does GREP_COLORS appear not to have a default value?
Because the environment variable GREP_COLORS can be used to override the existing default colors. It doesn't mean that it must be used.
The GNU grep default colors are defined into grep.c:
/* The color strings used for matched text.
The user can overwrite them using the deprecated
environment variable GREP_COLOR or the new GREP_COLORS. */
static const char *selected_match_color = "01;31"; /* bold red */
static const char *context_match_color = "01;31"; /* bold red */
/* Other colors. Defaults look damn good. */
static const char *filename_color = "35"; /* magenta */
static const char *line_num_color = "32"; /* green */
static const char *byte_num_color = "32"; /* green */
static const char *sep_color = "36"; /* cyan */
static const char *selected_line_color = ""; /* default color pair */
static const char *context_line_color = ""; /* default color pair */
and later there is a function parse_grep_colors (void) trying to get a value from GREP_COLORS environment variable. If it's empty or if its syntax is not valid, it will be ignored. For example if you set GREP_COLORS='random text', it will be ignored.
-
Very helpful! Thanks! Since
grep.cdoesn't appear to be on my system, I'm assuming I would need to recompilegrepfrom source in order to change the default via this file. Is that correct?Mark Pauley– Mark Pauley2022-06-06 18:37:40 +00:00Commented Jun 6, 2022 at 18:37 -
1You don't need to recomplile
grep, grep colors are totally configurable. If you want anygrepcommand in any interactive shell of your user to use different colors, just add into your./bashrcfile:export GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36'andsourceit. Change the numbers above to the new values you like.man grepand search forGREP_COLORSto see the syntax and how to set this variable.thanasisp– thanasisp2022-06-06 18:59:36 +00:00Commented Jun 6, 2022 at 18:59
grep's builtin defaults, so if a distro is happy with those, why should it set that variable?grepuses the variable isn't enough to make it appear in other processes. (Or even ingrepitself, unless it sets it explicitly, but it doesn't really need to.)