how to grep with color (--color=always) except when redirecting the output to a file

Is there a trick (probably a zsh function) to make a single grep command behave this way?

  1. if grep output is written to the terminal, or is piped to another command (usually less -R) -> use color

  2. if grep output is written to a file -> don't use color

The problem with grep --color=always is that it behaves incorrectly in case 2.

EDIT - Let's put it another way:

  • I need mygrep "a" file.txt | less -R to output colors.
  • I need mygrep "a" file.txt > output.txt to output NO colors.

How should mygrep be defined in my .zshrc?



Solution 1:

In my Kubuntu [ -f /dev/stdout ] can be used to tell if stdout is a regular file. This leads to the following shell function:

mygrep() {
   if [ -f /dev/stdout ]; then
      grep --color=never "$@"
   else
      grep --color=always "$@"
   fi
}

There's nothing specific to zsh here. The question is tagged linux, the function should work in Linux. In general (in other systems) experiences with /dev/stdout may vary.