55

I recently found that on Mac OS X I can set this up in my shell ~/.profile so that when I use grep it will print the matches in color (white one red).

alias grep='GREP_COLOR="1;37;41" LANG=C grep --color=auto'

But setting up an alias seems like kind of a hack way to do this. Previously I had tried with no luck:

export GREP_COLOR=always           # works fine in Linux

And then I also tried:

export GREP_COLOR="1;37;41"

Is there a better way to do this than setting up an alias?

3
  • I don't see the point of your question. An alias is how you do this. That's what it's for. export the environment variable e.g. in .bash_profile, and define alias grep='grep --color', and you're done.
    – Daniel Beck
    Apr 25, 2012 at 18:05
  • 3
  • tl/dr: just do this instead: export GREP_OPTIONS='--color=auto'
    – MarkHu
    May 7, 2021 at 0:22

2 Answers 2

83

Per Grep_color on mac as suggested by @lupincho, this seems to work fine and does not use an alias:

export GREP_OPTIONS='--color=always'
export GREP_COLOR='1;35;40'
9
  • 15
    Have a +1 for this as a good solution, however setting GREP_OPTIONS leads to grep: warning: GREP_OPTIONS is deprecated; please use an alias or script. Something like this is now preferred: alias grep="`which grep` --color=always" Nov 6, 2015 at 12:06
  • 2
    @joelittlejohn doesn't work when using grep in pipes with xargs, eg: find /usr/share -name '*.txt' |xargs grep testing
    – rfabbri
    May 27, 2016 at 15:29
  • 1
    @rfabbri I guess that's one to take up with the grep team who deprecated this :) Oct 5, 2016 at 12:16
  • 8
    --color=alwaysis dangerous. Scripts run from the shell will also inherit the option and cause very mysterious failures when grep starts injecting color codes to output inside scripts. --color=auto doesn't cause this problem.
    – Sampo
    Sep 6, 2017 at 13:24
  • 3
    @joelittlejohn that is not true for the default grep in OSX. Even on High Sierra 10.13, it uses FREEBSD grep 2.5.1 which HAS NOT depreciated GREP_OPTIONS. That's only true in gnu/grep
    – cde
    Feb 3, 2018 at 2:32
0

On macOS Catalina with grep (BSD grep) 2.5.1-FreeBSD I use the --colour argument when calling grep to activate highlighting.

grep --colour thon /usr/share/dict/words

I found this option when I ran 'man grep' after finding this thread. It seems odd the spelling of the argument is '--colour', and not '--color'. This command prints the results with text highlighted in red.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .