bash和zsh中的可移植数组索引

bash和zsh中的可移植数组索引

本文介绍了bash和zsh中的可移植数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组索引在 bash 中基于 0 ,在 zsh 中基于 1 (除非选项 KSH_ARRAYS 已设置.)

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

推荐答案

TL; DR:

要始终获得一致的行为,请使用:

TL;DR:

To always get consistent behaviour, use:

${array[@]:offset:length}


说明

对于同时适用于 bash zsh 的代码,您需要使用 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.

即使对于仅 zsh 的代码,由于 zsh ',您仍然需要执行此操作(或使用 emulate -LR zsh )数组的下标基础由选项 KSH_ARRAYS .

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}

在这里, array [@] 是所有元素, 0 是偏移量(始终始终从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.

这篇关于bash和zsh中的可移植数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 21:14