简体   繁体   中英

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?

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'`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM