Skip to content
Advertisement

Bash for loop on two arrays

I have two arrays that I need to iterate over but I can’t figure out how to get the combination of both arrays…

declare -a things=(
"apple"
"cider"
"OJ"
)
declare -a numbers=(
"1"
"2"
"3"
"4"
"5
"6"
)


for i in "${things[@]}"; do
  echo $i $numbers
done

Expecting:
apple 1
apple 2
apple 3
apple 4
apple 5
apple 6
cider 1
cider 2
cider 3
... etc

Advertisement

Answer

declare -a things=(
"apple"
"cider"
"OJ"
)
declare -a numbers=(
"1"
"2"
"3"
"4"
"5"
"6"
)


for i in "${things[@]}"; do
  for number in "${numbers[@]}"; do
    echo "$i" "$number"
  done
done
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement