Tom Hale
Tom Hale

Reputation: 46813

Portable array indexing in both bash and zsh

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

Answers (1)

Tom Hale
Tom Hale

Reputation: 46813

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.

Upvotes: 3

Related Questions