匿名関数を使用して、変数のスコープを提供できます。から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
、変数は現在のインタラクティブセッションでのみ表示され、サブシェルにエクスポートされるべきではありません。
terdonが彼のコメントで説明したように:export -n
in bash
は「export」プロパティを変数から削除するだけなので、export -n GREP_OPTIONS=--color=always
exportをまったく使用しないのと同じGREP_OPTIONS=--color=always
です- 。
つまり、目的の動作を得るには、を使用しないでくださいexport
。代わりに、あなたには.zshrc
、あなたが持っている必要があります
GREP_OPTIONS=--color=always
これにより、実行するすべての(対話式、非ログイン)シェルで変数を使用できるようになりますが、子シェルにはエクスポートされません。
export -n
エクスポートされた変数をアンエクスポートするだけです。