Using arrays in ZSH
This behaviour might surprise you, depending on your programming background, but it is the desired one.
From man zshparam
regarding the form ${TOKENARRAY[exp]}
:
A subscript of the form
[exp]
selects the single element exp, where exp is an arithmetic expression which will be subject to arithmetic expansion as if it were surrounded by$((...))
. The elements are numbered beginning with 1, unless the KSH_ARRAYS option is set in which case they are numbered from zero.
The syntax ${TOKENARRAY:0}
is documented in man zshexpn
:
${name:offset}
(...) A positive offset is always treated as the offset of a character or element in name from the first character or element of the array (this is different from native zsh subscript notation). Hence 0 refers to the first character or element regardless of the setting of the option KSH_ARRAYS.
So this in principle gives your complete array (not only the first element), starting from the first character.
So, when you state
This script is supposed to work in bash, but it's not working in zsh.
you might want to consider emulate sh
in your script, which enables the KSH_ARRAY option besides other ones (emulate -l sh
gives you a list) or just setopt KSH_ARRAYS
.
For a script that works in both bash and zsh, you need to use a more complicated syntax.
Eg, to reference the first element in an array:
${array[@]:0:1}
Here, array[@]
is all the elements, 0
is the offset (which always is 0-based), and 1
is the number of elements desired.