How can I grep with color in Mac OS X's terminal?

42

7

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?

cwd

Posted 2012-04-25T18:01:06.307

Reputation: 13 508

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 – 2012-04-25T18:05:38.923

2

check this: http://unix.stackexchange.com/questions/34790/grep-color-on-mac

– lupincho – 2012-04-25T18:35:45.010

Answers

64

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'

Steve Brown

Posted 2012-04-25T18:01:06.307

Reputation: 693

Didn't work for me. :( – trusktr – 2014-11-25T23:04:58.513

Did you restart your terminal ? – Mike Nguyen – 2015-07-16T08:31:03.823

13Have 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"` – joelittlejohn – 2015-11-06T12:06:16.840

2@joelittlejohn doesn't work when using grep in pipes with xargs, eg: find /usr/share -name '*.txt' |xargs grep testing – rfabbri – 2016-05-27T15:29:51.790

@joelittlejohn's comment makes this a non-starter for me; it prints that warning on every grep command (so, many, many times on a find operation). – rcreswick – 2016-10-04T22:11:26.617

1@rfabbri I guess that's one to take up with the grep team who deprecated this :) – joelittlejohn – 2016-10-05T12:16:49.890

For some reason for me I did not see an effect after I opened a new terminal, but source ~/.bashrc did it. – Akavall – 2016-12-01T18:14:40.360

4--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 – 2017-09-06T13:24:28.480

2@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 – 2018-02-03T02:32:06.967