我需要有关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。有人可以解释一下这是什么吗?
arr=(file*)
,并从index=0
开始。 - anubhavatype ls
会输出什么? - that other guyzsh
?在bash
中,数组是从零开始的;而在zsh
中,数组则是从一开始的。 - chepnerbash
来执行的,但是您的命令行示例表明您正在使用zsh
。echo $ARR
输出fileA
还是fileA fileB
? - chepner