运维

Shell脚本中使用for循环遍历数组的七种方法

在 Shell 脚本中,for 循环可以使用多种方式遍历数组。本文例举一些常见的实现方法:

1. 直接遍历数组元素

for item in "${my_array[@]}"; do
    echo "$item"
done

说明:${my_array[@]} 展开数组的所有元素,一个个传给 for 循环。

2. 通过数组索引遍历

for i in "${!my_array[@]}"; do
    echo "Index $i: ${my_array[i]}"
done

说明:${!my_array[@]} 获取数组的所有索引,用于按位置访问元素。

3. 使用传统 C 风格的 for 循环

for ((i = 0; i < ${#my_array[@]}; i++)); do
    echo "Index $i: ${my_array[i]}"
done

说明:
${#my_array[@]} 获取数组的长度。
((...)) 进行 C 风格的循环迭代。

4. 逆序遍历数组

for ((i = ${#my_array[@]} - 1; i >= 0; i--)); do
    echo "Index $i: ${my_array[i]}"
done

说明:通过索引从数组尾部向前遍历。

5. 遍历带条件检查

my_array=(a b c di Bi ei Bc)

for item in "${my_array[@]}"; do
    if [[ $item == B* ]]; then
        echo "匹配的元素: $item"
    fi
done

说明:结合 if 条件语句,筛选符合特定条件的元素。

6. 遍历多维数组(嵌套循环)

multi_array=( 
    "Row1: Apple Banana"
    "Row2: Cherry Date"
)

for row in "${multi_array[@]}"; do
    for element in $row; do
        echo "$element"
    done
done

说明:用于多维数组或需要逐层处理的数据。

7. 以指定步长遍历数组

step=2
for ((i = 0; i < ${#my_array[@]}; i+=step)); do
    echo "Index $i: ${my_array[i]}"
done

说明:可以通过控制索引增量(如步长为 2)跳跃式遍历数组。

回复 / 取消回复

  1. vevqulnoch
    Sogo 10

    2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
    新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
    新车首发,新的一年,只带想赚米的人coinsrore.com
    新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
    做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
    新车上路,只带前10个人coinsrore.com
    新盘首开 新盘首开 征召客户!!!coinsrore.com
    新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
    新车即将上线 真正的项目,期待你的参与coinsrore.com
    新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
    新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com

  2. pzvaskvtrm
    Sogo 10

    新车上路,只带前10个人

  3. wryktfhwhl
    Sogo 10

    文字如刀,剖开表象直抵本质。

  4. ysmycyroys
    Sogo 10

    这篇文章提供了宝贵的经验和见解,对读者有很大的启发和帮助。

  5. Hyus
    Firefox 131 10

    一键三连支持!

This is just a placeholder img.