Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: All combinations of variables

I want to generate all the combinations of a set of variables.

I ended up with the following:

a="A"
b="B"
c="C"
d="D"
e="E"
f="F"

echo {$a,$b,$c,$d,$e,$f} $a{$b,$c,$d,$e,$f} $b{$c,$d,$e,$f} $c{$d,$e,$f} $d{$e,$f} $e$f $a$b{$c,$d,$e,$f} $b$c{$d,$e,$f} $c$d{$e,$f} $d$e$f $a$b$c$d{$e,$f} $b$c$d$e$f $a$b$c$d$e$f

This generates the following output:

A B C D E F AB AC AD AE AF BC BD BE BF CD CE CF DE DF EF ABC ABD ABE ABF BCD BCE BCF CDE CDF DEF ABCDE ABCDF BCDEF ABCDEF

Is there a more concise and elegant way of doing this in bash?

like image 465
dcirillo Avatar asked Oct 15 '22 11:10

dcirillo


1 Answers

With the script

echo {'','a'}{'','b'}{'','c'}{'','d'}{'','e'}{'','f'}

you will get

 f e ef d df de def c cf ce cef cd cdf cde cdef b bf be bef bd bdf bde bdef bc bcf bce bcef bcd bcdf bcde bcdef a af ae aef ad adf ade adef ac acf ace acef acd acdf acde acdef ab abf abe abef abd abdf abde abdef abc abcf abce abcef abcd abcdf abcde abcdef

Though not in order, this does what you may want. So you can use

echo {'',$a}{'',$b}{'',$c}{'',$d}{'',$e}{'',$f}

If you do not wish to type so many {'',$x} in the script you may even use eval:

eval `echo echo "{'',$"{a..f}"}" | sed 's/ //2g'`
like image 171
dibery Avatar answered Oct 19 '22 00:10

dibery