5

What is the default color behavior for grep --color if no [=WHEN] is specified?

The grep man page states:

--color[=WHEN], --colour[=WHEN]

    Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal.  ...  WHEN is never, always, or auto.

Does the default [=WHEN] for grep --color become:

grep --color=auto

or

grep --color=always

or does it depend on implementation and platform?

In my tests on Ubuntu 14.04 with GNU grep 2.16:

echo "foo bar" | \grep --color foo

results in foobar, while

echo "foo bar" | \grep --color foo | \grep --color bar

results in foobar, so it appears that grep --color=auto is in effect here. I have not tested this on Windows or Mac, however; I don't know if this behavior is universal.

This default for [=WHEN] is a little different from ls --color where the man page for ls states:

--color[=WHEN]

    colorize the output.  WHEN defaults to always or can be never or auto.

Here, the behavior of the missing WHEN is explicit.

16

It defaults to auto.

grep --color is the same as writing --color=auto.

This seems to be deficiently documented, or they consider the simple --color deprecated, but that can be seen both from testing and from its source code:

  case COLOR_OPTION:
    if (optarg)
      {
        if (!strcasecmp (optarg, "always") || !strcasecmp (optarg, "yes")
            || !strcasecmp (optarg, "force"))
          color_option = 1;
        else if (!strcasecmp (optarg, "never") || !strcasecmp (optarg, "no")
                 || !strcasecmp (optarg, "none"))
          color_option = 0;
        else if (!strcasecmp (optarg, "auto") || !strcasecmp (optarg, "tty")
                 || !strcasecmp (optarg, "if-tty"))
          color_option = 2;
        else
          show_help = 1;
      }
    else
      color_option = 2;
    break;

Notice that the lack of an optarg results in the same as it being equal to auto or tty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.