Shell – Local variables in zsh: what is the equivalent of bash’s “export -n” in zsh

environment-variablesshell-scriptzsh

I'm trying to contain the scope of a variable to a shell, and not have children see it, in zsh. For example, I type this in .zshrc:

GREP_OPTIONS=--color=always

But if I run a shell script with the following:

#!/bin/bash
echo $GREP_OPTIONS

The output is:

--color=always

while I want it to be null (the shell script above should not see the GREP_OPTIONS variable at all).

In bash, one can say: export -n GREP_OPTIONS=--color=always, which will prevent this from happening. How do I accomplish this in zsh?

Best Answer

export in zsh is shorthand for typeset -gx, where the attribute g means “global” (as opposed to local to a function) and the attribute x means “exported” (i.e. in the environment). Thus:

typeset +x GREP_OPTIONS

This also works in ksh and bash.

If you never export GREP_OPTIONS in the first place, you don't need to unexport it.

You can also use the indirect, portable way: unsetting a variable unexports it. In ksh/bash/zsh, this doesn't work if the variable is read-only.

tmp=$GREP_OPTIONS
unset GREP_OPTIONS
GREP_OPTIONS=$tmp
Related Question