Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Is there a way to generate cartesian product of arrays without using loops in bash?

One can use curly brackets to do a similar thing:

echo {a,b,c}+{1,2,3}
a+1 a+2 a+3 b+1 b+2 b+3 c+1 c+2 c+3

but I need to use arrays as inputs, and most obvious tricks fail me.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

You could use brace expansion. But it's ugly. You need to use eval, since brace expansion happens before (array) variable expansion. And "${var[*]}" with IFS=, to create the commas.

Consider a command to generate the string

echo {a,b,c}+{1,2,3}

Assuming the arrays are called letters and numbers, you could do that using the "${var[*]}" notation, with IFS=, to insert commas between the elements instead of spaces.

letters=(a b c)
numbers=(1 2 3)
IFS=,
echo {"${letters[*]}"}+{"${numbers[*]}"}

Which prints

{a,b,c}+{1,2,3}

Now add eval, so it runs that string as a command

eval echo {"${letters[*]}"}+{"${numbers[*]}"}

And you get

a+1 a+2 a+3 b+1 b+2 b+3 c+1 c+2 c+3
share|improve this answer
1  
Thanks a lot for both the solution and the explanation! –  xl0 Oct 27 '13 at 16:01
1  
The only problem is with arrays containing just 1 element, as bash won't expand {a}+{1,2,3} properly. –  xl0 Oct 27 '13 at 16:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.