Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

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?

like image 514
Zifei Tong Avatar asked Aug 20 '10 14:08

Zifei Tong


People also ask

What is Foo in shell script?

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. Foo and other words like it are formally known as metasyntactic variables.

What does local mean in Shell?

A variable declared as local is one that is visible only within the block of code in which it appears. It has local "scope". In a function, a local variable has meaning only within that function block.

What does bash local do?

Local Bash Variables local is a keyword which is used to declare the local variables. In a function, a local variable has meaning only within that function block.


2 Answers

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.

like image 188
paxdiablo Avatar answered Oct 10 '22 04:10

paxdiablo


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.

like image 43
Dennis Williamson Avatar answered Oct 10 '22 03:10

Dennis Williamson