Skip to content
Advertisement

Can not assign function parameters to local array variable in `Zsh`

I just try to assign parameters of function as local array variable, I tried

$test_print(){local foo=( "${@:1}" ); echo $foo[*]}; test_print a b c

I got

test_print: bad pattern: foo=( a

But if I remove local keyword

$test_print(){foo=( "${@:1}" ); echo $foo[*]}; test_print a b c

It’s work

a b c

What is a problem here? How can I keep my array to local variable?

Additional information

I tried this on bash shell, it’s work well either as local or global variable.

Advertisement

Answer

In order to make the wanted assignment, you have to separate the declaration of foo and the assignment of the value into two command:

test_print(){local foo; foo=( "${@:1}" ); echo $foo[*]}; test_print a b c

According to the ZSH Manual local behaves like typeset:

**local [ {+|-}AEFHUahlprtux ] [ -LRZi [ n ]] [ name[=value] ] …

Same as typeset, except that the options -g, and -f are not permitted. In this case the -x option does not force the use of -g, i.e. exported variables will be local to functions.

In the the paragraph on typeset it says:

Note that arrays currently cannot be assigned in typeset expressions, only scalars and integers.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement