Portable array indexing in both bash and zsh

♀尐吖头ヾ 提交于 2019-12-11 15:31:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!