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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM