14

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 Answers 2

17

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.

1
  • 1
    This is what I really wanted to know.
    – To1ne
    Commented Jul 23, 2013 at 12:09
16

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.

4
  • 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
    Commented Aug 20, 2010 at 14:51
  • @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
    Commented Aug 20, 2010 at 14:52
  • What a mistake I just made. Thank you, paxdiablo.
    – Zifei Tong
    Commented Aug 20, 2010 at 15:06
  • 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
    Commented Aug 20, 2010 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.