Answers:
export
在zsh中,它是的简写typeset -gx
,其中属性g
表示“全局”(相对于函数的局部),而属性x
表示“导出”(即,在环境中)。从而:
typeset +x GREP_OPTIONS
这也适用于ksh和bash。
如果您从未GREP_OPTIONS
从头开始导出,则无需取消导出。
您还可以使用间接的,可移植的方式:取消设置变量会取消导出它。在ksh / bash / zsh中,如果变量为只读,则此方法无效。
tmp=$GREP_OPTIONS
unset GREP_OPTIONS
GREP_OPTIONS=$tmp
env -u GREP_OPTIONS your-script
一些env
实现(任何shell)。或者(unset GREP_OPTIONS; exec your-script)
export_all
(-a
)选项?但是即使那样,typeset +x GREP_OPTIONS
仍会取消导出变量。如果找不到问题,请尝试二进制搜索:备份您的文件.zshrc
,删除后半部分,看问题是否仍然存在,然后追加第三季度或减少到第一季度并重复。
您可以使用匿名函数来提供变量的作用域。来自man zshall
:
ANONYMOUS FUNCTIONS
If no name is given for a function, it is `anonymous' and is handled
specially. Either form of function definition may be used: a `()' with
no preceding name, or a `function' with an immediately following open
brace. The function is executed immediately at the point of definition
and is not stored for future use. The function name is set to
`(anon)'.
Arguments to the function may be specified as words following the clos‐
ing brace defining the function, hence if there are none no arguments
(other than $0) are set. This is a difference from the way other func‐
tions are parsed: normal function definitions may be followed by cer‐
tain keywords such as `else' or `fi', which will be treated as argu‐
ments to anonymous functions, so that a newline or semicolon is needed
to force keyword interpretation.
Note also that the argument list of any enclosing script or function is
hidden (as would be the case for any other function called at this
point).
Redirections may be applied to the anonymous function in the same man‐
ner as to a current-shell structure enclosed in braces. The main use
of anonymous functions is to provide a scope for local variables. This
is particularly convenient in start-up files as these do not provide
their own local variable scope.
For example,
variable=outside
function {
local variable=inside
print "I am $variable with arguments $*"
} this and that
print "I am $variable"
outputs the following:
I am inside with arguments this and that
I am outside
Note that function definitions with arguments that expand to nothing,
for example `name=; function $name { ... }', are not treated as anony‐
mous functions. Instead, they are treated as normal function defini‐
tions where the definition is silently discarded.
但是,从那个分开-如果你不使用export
你的.zshrc
所有,该变量只应在当前的交互式会话可见的,它不应该被导出到子shell。
正如terdon在他的评论中解释的那样:export -n
in bash
只会导致从变量中删除“ export”属性,因此using export -n GREP_OPTIONS=--color=always
等于完全不使用export- GREP_OPTIONS=--color=always
。
换句话说,要获得所需的行为,请不要使用export
。相反,在您的中.zshrc
,您应该有
GREP_OPTIONS=--color=always
这将使变量对您运行的所有(交互式,非登录)shell都可用,就像您希望的那样,但不会将其导出到子shell。
export -n
只是取消导出导出的变量。