17

Because I'm lazy.... any time I want to use grep, I want it to be grep -n --colour. Is there a way to permanantly map this?

  • 6
    +1 for "Because I'm lazy...". Ever considered a career as a developer? :) – dr Hannibal Lecter Oct 13 '10 at 17:34
31

In your $HOME/.bashrc file, add:

export GREP_OPTIONS="-n --color"

This will work with egrep too and in aliases that use grep.

Update: GREP_OPTIONS is deprecated from grep 2.21 on and if you use this solution you will see the following warning:

grep: warning: GREP_OPTIONS is deprecated; please use an alias or script

The best solution is to therefore follow maco's advice in his answer. Or switch to using ag, which outputs in color by default.

  • respect. – myusuf3 Aug 13 '10 at 16:57
  • 4
    Respect but no upvote, eh? ;-) – richq Aug 13 '10 at 17:08
  • 1
    Aliases can be used after a pipe just fine. They just don't recurse. – maco Aug 13 '10 at 17:35
  • 1
    Hey hey, I upvoted. I like this better than alias. – Dmitriy Likhten Aug 13 '10 at 19:37
  • @marco: you're right (with bash) - I was thinking of csh, where they can't. Oops! – richq Aug 13 '10 at 20:45
29

Edit ~/.bash_aliases Add a line that says:

alias grep='grep -n --color'

~/.bash_aliases is automatically included by ~/.bashrc if it exists

  • 8
    Or add the line in .profile if you want it to work in all shells not just bash. – LassePoulsen Aug 13 '10 at 22:16
  • 1
    this won't work with xargs eg: find /usr/share -name '*.txt' |xargs grep testing – rfabbri May 27 '16 at 15:22
2

you can modify the file .bashrc located in your home directory defining an alias, which will override any default setting:

alias grep='grep -n --color'

after the change close and open the terminal again because the file is read only when you open the terminal.

If you take a look on the file .bashrc you will found more default aliases like:

alias ll='ls -l'

alias la='ls -A'

alias l='ls -CF'

0

Create a script in addition to an alias mentioned in the other answers. An alias by itself won't always work, and a script layer is fast enough for human readable output anyways.

Choose a short name, like cgrep:

#!/bin/sh
grep --color -n "$@"

Place it in your path, say ~/bin (if you read UPE this is in your path :). Then stuff like this will work:

find /usr/share -name '*.txt' | xargs cgrep testing

I'm still not so happy, I too wanted grep to always color when stdout to a terminal without selectively typing cgrep.

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.