问题
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
回答1:
TL;DR:
To always get consistent behaviour, use:
${array[@]:offset:length}
Explanation
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.
来源:https://stackoverflow.com/questions/56310835/portable-array-indexing-in-both-bash-and-zsh