Francisco Leon
Francisco Leon

Reputation: 78

How to initialize array from array in zsh?

My script test.zsh:

args=$@
argss=($@)
echo ${@:2}
echo ${args:2}
echo ${argss:2}

The output:

$ ./test.zsh foo bar foobar
bar foobar
o bar foobar
o

It looks like args is being initialized as the string of $@ instead of as an array. How do I initialize args as an array? ($@) does not seem to work either

Upvotes: 1

Views: 835

Answers (1)

yut23
yut23

Reputation: 3064

You need to put parentheses around $@ to make args an array:

args=($@)

In other shells, you should also put quotes around it (args=("$@")) to avoid word splitting, but this is disabled by default in zsh (see the option SH_WORD_SPLIT).

Note that ${@:2} will give you $1 $2 $3 ..., while ${args:2} will give $2 $3 ..., because zsh prepends $0 to $@ when you use that form of parameter subscripting for compatibility with other shells. The preferred zsh way to subscript arrays is ${arr[start,end]}, where end is inclusive and may be negative. ${args[1,-1]} and ${args[@]} will expand to the same thing.

Upvotes: 2

Related Questions