0

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

2 Answers 2

3
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
Sign up to request clarification or add additional context in comments.

1 Comment

You should quote the variables in the echo command: there may be whitespace or globbing characters in the array elements. (obviously not here, but in general)
2

To get that output, you need to loop only first array and use printf:

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

# loop thru 1st array and use printf to print all values from 2nd
for i in "${things[@]}"; do printf "$i %s\n" "${numbers[@]}"; done

apple 1
apple 2
apple 3
apple 4
apple 5
apple 6
cider 1
cider 2
cider 3
cider 4
cider 5
cider 6
OJ 1
OJ 2
OJ 3
OJ 4
OJ 5
OJ 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.