gpt4 book ai didi

linux - bash 脚本和 zsh shell 中数组的行为(起始索引 0 或 1?)

转载 作者:IT王子 更新时间:2023-10-29 00:31:29 30 4
gpt4 key购买 nike

我需要解释数组在 shell 脚本中的以下行为:

假设给出以下内容:

arber@host ~> ls
fileA fileB script.sh

现在我可以执行以下命令:

arber@host ~> ARR=($(ls -d file*))
arber@host ~> echo ${ARR[0]} # start index 0

arber@host ~> echo ${ARR[1]} # start index 1
fileA
arber@host ~> echo ${ARR[2]} # start index 2
fileB

但是当我通过 script.sh 执行此操作时,它的行为有所不同(起始索引 = 0):

arber@host ~> cat script.sh
#!/bin/bash
ARR=($(ls -d file*))

# get length of an array
aLen=${#ARR[@]}

# use for loop read all items (START INDEX 0)
for (( i=0; i<${aLen}; i++ ));
do
echo ${ARR[$i]}
done

结果如下:

arber@host ~> ./script.sh
fileA
fileB

我使用 Ubuntu 18.04 LTS 和 zsh。谁能解释一下?

最佳答案

长话短说:

  • bash 数组索引从 0 开始(始终)
  • zsh 数组索引从 1 开始(除非设置了 option KSH_ARRAYS)

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

${array[@]:offset:length}

解释

对于同时适用于 bashzsh 的代码,您需要使用 offset:length 语法而不是 [下标]语法。

即使对于 zsh-only 代码,您仍然需要这样做(或使用 emulate -LR zsh),因为 zsh' s 数组下标基础由 KSH_ARRAYS 选项确定。

例如,引用数组中的第一个元素:

${array[@]:0:1}

这里,array[@] 是所有元素,0 是偏移量(总是从 0 开始),1 是所需元素的数量。

关于linux - bash 脚本和 zsh shell 中数组的行为(起始索引 0 或 1?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50427449/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com