I define a list in bash like this:

list="element1 element_2 my_element_3 element04"

and I want to do a loop where I iterate through all possible pair combinations. In Perl, I would use a while/foreach with a shift on the list like this:

while (my $element1 = shift (@list)) {
  foreach my $element2 (@list) {
      print "$element1 - $element2\n";
  }
}

I don't want the same element in the pair and don't care about the order of the pairs, so if the list is "A B C", the result should be:

A - B
A - C
B - C

How can I do the equivalent in bash?

link|improve this question

73% accept rate
feedback

2 Answers

up vote 5 down vote accepted

The simplest approach seems to be to use positional parameters.

set -- value1 value2 "value with spaces"
for a; do
    shift
    for b; do
        printf "%s - %s\n" "$a" "$b"
    done
done
link|improve this answer
hmmmm, just to clarify, I don't want the same element in the pair and don't care about the order of the pairs, I've edited my question now. – 130490868091234 Aug 2 '11 at 13:12
I just saw the shift in your original question as well. Updated answer to match. – jw013 Aug 2 '11 at 13:21
feedback

dump the output to standard out, pipe to sort -u

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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