Reputation: 46813
Array indexing is 0
-based in bash
, and 1
-based in zsh
(unless option KSH_ARRAYS
is set).
As an example: To access the first element of an array, is there something nicer than:
if [ -n $BASH_VERSION ]; then
echo ${array[0]}
else
echo ${array[1]}
fi
Upvotes: 1
Views: 457
Reputation: 46813
To always get consistent behaviour, use:
${array[@]:offset:length}
For code which works in both bash
and zsh
, you need to use the offset:length
syntax rather than the [subscript]
syntax.
Even for zsh
-only code, you'll still need to do this (or use emulate -LR zsh
) since zsh
's array subscripting basis is determined by the option KSH_ARRAYS
.
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.
Upvotes: 3