zewiblzd
zewiblzd

Reputation: 13

Bash: nested for loop + middle loop contains two arrays?

Maybe I'm over-thinking this but here's my desired output:

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

Here's what I started. I got to the second for loop and totally lost my mind trying to find the solution.

#!/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

Upvotes: 0

Views: 50

Answers (1)

choroba
choroba

Reputation: 241808

You can't have more than one in in a for clause.

If you need to iterate two arrays simultaneously, iterate over their indices:

#! /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

Upvotes: 1

Related Questions