shell遍歷多個數組
阿新 • • 發佈:2021-08-08
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]#