Shell 数组遍历

通常使用for、while遍历数组。

例1:通过for与下标遍历数组。

arr1=("xiaobuteach.com" "Linux" "Shell" "HTML" "CSS" "JavaScript")

for ((i=0;i<${#arr1[*]};i++))
do
   echo "第${i}个元素:${arr1[i]}"
done

img

例2:通过for in遍历数组。

arr1=("xiaobuteach.com" "Linux" "Shell" "HTML" "CSS" "JavaScript")

for item in ${arr1[*]}
do
    echo "元素:${item}"
done

${arr1[*]}也可以使用${arr1[@]}

img

例3:for in 下标集合遍历数组

arr1=("xiaobuteach.com" "Linux" "Shell" "HTML" "CSS" "JavaScript")

for index in ${!arr1[*]}
do
    echo "下标:$index,元素:${arr1[index]}"
done

${!arr1[*]返回所有下标

img

例4:while遍历数组

while条件使用(( ))进行数学计算

arr1=("xiaobuteach.com" "Linux" "Shell" "HTML" "CSS" "JavaScript")
i=0
while ((i<${#arr1[*]}))
do
    echo "第${i}个元素:${arr1[i]}"
    ((i++))
done

例5:while遍数组2

while条件使用test命令或[ ]

arr1=("xiaobuteach.com" "Linux" "Shell" "HTML" "CSS" "JavaScript")
i=0

while [ $i -lt ${#arr1[*]} ]
do
    echo "第${i}个元素:${arr1[i]}"
    let i++
done