我需要解释 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。有人可以解释一下吗?