Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I was playing around with setting GREP_OPTIONS and couldn't get it to work. Just curious as to why.

Simple test commands output:

richard@ubuntu:~$ echo $GREP_OPTIONS

richard@ubuntu:~$ 

richard@ubuntu:~$ ls | grep o 
Desktop
downloads
Dropbox
ebooks
workspace

richard@ubuntu:~$ ls | grep o --color=always | less -R 

richard@ubuntu:~$ export GREP_OPTIONS="--color=always" 
richard@ubuntu:~$ ls | grep o  | less -R 
  1. The 1st grep outputs to the terminal in color (each 'o' is red)
  2. The 2nd grep outputs via less in color (same as 1)
  3. But the 3rd grep outputs to less but in black & white – but this should be in color.

So it appears that grep is ignoring GREP_OPTIONS. Is that a bug or am I doing something wrong?

(Ubuntu 12.04.2, GNU grep 2.10)

share|improve this question

1 Answer 1

up vote 4 down vote accepted

If grep o produces color output, then either grep is an alias to grep --color=auto or grep --color=always (or possibly more options), or GREP_OPTIONS is set to a value that contains --color=auto or --color=always. Since $GREP_OPTIONS is empty, it must be the alias.

Since grep o | less -R doesn't show colors, the alias must be to grep --color=auto (a sensible choice). With the alias, the grep command always receives the --color option on the command line, and this takes precedence over the environment variable.

If you want to use the environment variable, remove the alias definition from your ~/.bashrc, or for one session run unalias grep. You can replace alias grep='grep --color=auto' by export GREP_OPTIONS='--color=auto': they have essentially the same meaning, except that: * setting GREP_OPTIONS to a different value only overrides the latter; * the alias only kicks in when you run grep from an interactive shell, whereas setting GREP_OPTIONS also applies when grep is run from scripts and other applications. (Never put --color=always in GREP_OPTIONS: it would break many programs that parse the output of grep.)

Note that the alias definition goes into ~/.bashrc (it's a shell setting), whereas the environment variable definition goes into ~/.profile (it's a session setting). See Alternative to .bashrc

If you want to run the unaliased command just once, run \grep instead of grep (quoting any part of the name bypasses the alias lookup).

share|improve this answer
    
Yes you're right, running \grep ... shows it correctly. Thanks for bonus tip for advising me against using "=always" in .bashrc. +1 –  Richard Mar 27 '13 at 0:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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