Anda bisa menggunakan fungsi anonim untuk memberikan cakupan variabel. Dari 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.
Tapi selain itu - jika Anda tidak menggunakan export
di Anda .zshrc
sama sekali, variabel hanya harus terlihat dalam sesi interaktif Anda saat ini, dan itu tidak boleh diekspor ke subkulit.
Seperti Terdon dijelaskan dalam komentarnya: export -n
di bash
hanya menyebabkan "ekspor" properti untuk dihapus dari variabel, sehingga menggunakan export -n GREP_OPTIONS=--color=always
setara dengan tidak menggunakan ekspor sama sekali - GREP_OPTIONS=--color=always
.
Dengan kata lain, untuk mendapatkan perilaku yang diinginkan, jangan gunakan export
. Sebaliknya, dalam diri Anda .zshrc
, Anda seharusnya memilikinya
GREP_OPTIONS=--color=always
Itu akan membuat variabel tersedia untuk semua shell (interaktif, non-login) yang Anda jalankan, seperti yang Anda inginkan, tetapi tidak akan diekspor ke shell anak.
export -n
cukup hapus ekspor variabel yang diekspor.