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

问题描述 投票:4回答:1

我需要解释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执行此操作时,它的行为会有所不同(Start Index = 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。有人可以解释一下吗?

linux bash shell ubuntu zsh
1个回答
4
投票

Arrays in Bash are indexed from zeroin zsh they're indexed from one

但是你不需要像这样的简单用例的索引。循环使用${array[@]}适用于:

files=(file*)
for f in "${files[@]}"; do
    echo "$f"
done

在zsh你也可以使用$files而不是"${files[@]}",但这在Bash中不起作用。 (并且它会删除空数组元素,但是你不会从文件名中获取任何内容。)


另外,不要使用$(ls file*),如果你有带空格的文件名,它会破坏(参见WordSpliting on BashGuide),并且开始时完全没用。

shell完全能够自己生成文件名。实际上会发生这种情况,shell会找到名称与file*匹配的所有文件,将它们传递给ls,而ls只是再打印出来供shell读取和处理。

© www.soinside.com 2019 - 2024. All rights reserved.