Bash:嵌套for循环+中间循环包含两个数组?

时间:2017-09-20 06:55:35

标签: arrays linux bash shell sh

也许我过度思考这个但是这是我想要的输出:

one four seven 
one five eight
one six nine
two four seven
two five eight
two six nine
three four seven
three five eight
three six nine

这是我开始的。我进入了第二个for循环,完全失去了我的想法,试图找到解决方案。

#!/bin/bash

declare -a aaa=("four" "five" "six")
declare -a bbb=("one" "two" "three")
declare -a ccc=("seven" "eight" "nine")


for bs in ${bbb[@]}; do
  for as in ${aaa[@]}, cs in ${ccc[@]}; do
    echo "$bs" "$as" "$cs"
  done
done

1 个答案:

答案 0 :(得分:1)

in条款中不能有for个。{/ p>

如果需要同时迭代两个数组,则迭代它们的索引:

#! /bin/bash

declare -a aaa=("four" "five" "six")
declare -a bbb=("one" "two" "three")
declare -a ccc=("seven" "eight" "nine")

for b in "${bbb[@]}" ; do
    for i in "${!aaa[@]}" ; do  # or ccc
        echo "$b" "${aaa[i]}" "${ccc[i]}"
    done
done