shell遍历多个数组

shell遍历多个数组

项目中拆分成多个微服务后,要shell启动多个服务,唯一的区别,就是启动类和环境不一样外,其他都是一样的,这样就抽出了2个数组,需要在一个for循环中遍历出来,demo如下:

[root@rocketmq-nameserver2 shell]# cat test6.sh
#!/bin/bash

a=(james  tom jack)
b=(1 2 3)

# seq 0 `expr ${#a[@]} - 1`
for i in $(seq 0 `expr ${#a[@]} - 1`); do
    _a=${a[i]}
    _b=${b[i]}
    echo $i, $_a, $_b
done

结果:

[root@rocketmq-nameserver2 shell]# sh test6.sh
0, james, 1
1, tom, 2
2, jack, 3

如果是单个数组的话:

[root@rocketmq-nameserver2 shell]# cat test5.sh
#!/bin/bash
day=(mon tue  wed thu fri sat sun)
for word in ${day[@]}
do
        echo $word
done
[root@rocketmq-nameserver2 shell]#

于是整合了一下,写了一个具体的demo

[root@rocketmq-nameserver2 shell]# cat base.conf
 a=(4 5 6)
 b=(1 2 3)

[root@rocketmq-nameserver2 shell]# cat test7.sh
#!/bin/bash
sum()
{
    echo "求两个数的和..."
    echo "两个数字分别为 $1 和 $2 "
    echo $(($1+$2))
}

test(){
  bash_path=$(cd "$(dirname "$0")";pwd)
  source $bash_path/base.conf
for i in $(seq 0 `expr ${#a[@]} - 1`); do
    c=${a[i]}
    d=${b[i]}
    sum $c $d
done
}

test
[root@rocketmq-nameserver2 shell]#

image-20210808212033099

posted @ 2021-08-08 21:21  天宇轩-王  阅读(822)  评论(3编辑  收藏  举报