tags:

views:

38

answers:

2

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?

+2  A: 

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.

paxdiablo
Thank you for your answer.I tested this code. function foo { local -a bar bar=42 zsh -c "echo bar is $bar" } foo.it returns> bar is 42.So in the sub-processes, variable `bar` act as a normal exported global variable?
Zifei Tong
@Zifei, see my update, it's `local -x` for exporting, `setopt -a` for `ALLEXPORT` (you probably don't want that on, it's better to keep namespaces as clean as possible).
paxdiablo
What a mistake I just made. Thank you, paxdiablo.
Zifei Tong
No probs. One other thing - I don't think bar _is_ being exported. Your argument `$bar` in `"echo bar is $bar"` is being interpreted in the _current_ shell, not the sub-shell. That subshell is getting `"echo bar is 42"` and acting on that.
paxdiablo
Thank you again, learned a lot.
Zifei Tong
+1  A: 

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.

Dennis Williamson