1

I have the following variable I want to set to make grep behave a certain way:

GREP_OPTIONS=--color=always

The problem is, I only want this environment variable to be set on the command line. I don't want this variable to be set when I run shell scripts. I have to export it (using 'export GREP_OPTIONS' in zsh) in order for grep to see it. However, that means that shell scripts will also 'inherit' this variable, which I don't want.

How do I handle this situation? Using an alias has the same problem (the shell script executes the alias).

3
  • No, shell scripts don't execute the alias (unless they are zsh scripts and you define the alias in ~/.zshenv (which you shouldn't)). Feb 5, 2014 at 10:21
  • I don't know how to do that in zsh but in bash you can test for the shell state (i in $-). Thus you could set GREP_OPTIONS depending on the result of this test. Feb 5, 2014 at 11:27
  • @HaukeLaging zsh also sets $-, you can do it in the same way.
    – terdon
    Feb 5, 2014 at 11:50

1 Answer 1

3

You have the answer, actually. Don't use the GREP_OPTIONS environment variable, use an alias for grep instead:

alias grep='grep --color=auto'

Aliases are normally defined in ~/.zshrc, which is not read when zsh executes a script.

3
  • Won't simply having GREP_OPTIONS=--color=always in .zshrc have exactly the same effect?
    – terdon
    Feb 5, 2014 at 12:11
  • 2
    @terdon It depends. The zsh will not read ~/.zshrc when executing a script. But if the script is run from an interactive shell (which will read ~/.zshrc), it will inherit this shell's environment including GREP_OPTIONS`.
    – Adaephon
    Feb 5, 2014 at 12:24
  • @terdon No. If GREP_OPTIONS is to have any effect, it has to be in the environment (an unexported shell variable has no effect), and then it will take effect whether invoked from the interactive shell or by a script. Feb 5, 2014 at 12:50

You must log in to answer this question.

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