Zifei Tong
Zifei Tong

Reputation: 1737

What does "local -a foo" mean in zsh?

Zsh manual mentions that option -a means ALL_EXPORT,

ALL_EXPORT (-a, ksh: -a)

  All parameters subsequently defined are automatically exported.  

While export makes the variable available to sub-processes, the how can the same variable foo be local?

Upvotes: 14

Views: 5035

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360325

In local -a, the -a has the same meaning as it does for typeset:

-a
The names refer to array parameters. An array parameter may be created this way, but it may not be assigned to in the typeset statement. When displaying, both normal and associative arrays are shown.

Upvotes: 17

paxdiablo
paxdiablo

Reputation: 882028

I think you might be confused on a number of fronts.

The ALL_EXPORT (-a) setting is for setopt, not local. To flag a variable for export with local, you use local -x.

And you're also confusing directions of propagation :-)

Defining a variable as local will prevent its lifetime from extending beyond the current function (outwards or upwards depending on how your mind thinks).

This does not affect the propagation of the variable to sub-processes run within the function (inwards or downwards).

For example, consider the following scripts qq.zsh:

function xyz {
    local LOCVAR1
    local -x LOCVAR2
    LOCVAR1=123
    LOCVAR2=456
    GLOBVAR=789
    zsh qq2.zsh
}

xyz
echo locvar1 is $LOCVAR1
echo locvar2 is $LOCVAR2
echo globvar is $GLOBVAR

and qq2.zsh:

echo subshell locvar1 is $LOCVAR1
echo subshell locvar2 is $LOCVAR2

When you run zsh qq.zsh, the output is:

subshell locvar1 is
subshell locvar2 is 456
locvar1 is
locvar2 is
globvar is 789

so you can see that neither local variable survives the return from the function. However, the auto-export of the local variables to a sub-process called within xyz is different. The one marked for export with local -x is available in the sub-shell, the other isn't.

Upvotes: 16

Related Questions