14

Bash's {} brace expansion syntax allows for creating easy permutations

# echo {b,c,d}{a,e,i,o,u}
ba be bi bo bu ca ce ci co cu da de di do du

However it's not clear to me if/how it's possible to use this along with arrays except in very awkward use of $() echo and eval

Is there a simple way to use arrays with curly brace (permutation) expansion?

For example sake, imagine something like (which does not work of course):

CONS=( b c d )
VOWEL=( a e i o u )

echo {${CONS[@]}}{${VOWEL[@]}}
2
  • it's working in GNU bash, version 4.2.24 Output root@router:~# echo {${CONS[@]}}{${VOWEL[@]}} {b c d}{a e i o u}. if you want different then let us know .. ` Sep 16, 2013 at 21:18
  • 4
    @RahulPatil the OP wants ba be bi bo bu ca ce ci co cu da de di do du.
    – terdon
    Sep 16, 2013 at 21:20

3 Answers 3

12

You might use eval with IFS=,; "${array[*]}" (which joins the values with commas) or just two for loops:

$ CONS=(b c d);VOWEL=(a e i o u)
$ IFS=,;eval echo "{${CONS[*]}}{${VOWEL[*]}}"
ba be bi bo bu ca ce ci co cu da de di do du
$ for c in "${CONS[@]}";do for v in "${VOWEL[@]}";do echo "$c$v";done;done|paste -sd' ' -
ba be bi bo bu ca ce ci co cu da de di do du
9

It's possible with zsh:

$ CONS=( b c d )
$ VOWEL=( a e i o u )
$ echo $^CONS$^VOWEL
ba be bi bo bu ca ce ci co cu da de di do du

Or es:

; VOWEL=( a e i o u )
; CONS=( b c d )
; echo $VOWEL^$CONS
ab ac ad eb ec ed ib ic id ob oc od ub uc ud

With bash or ksh93, you'd have to do something convoluted like:

VOWEL=( a e i o u )
CONS=( b c d )
qVOWEL=$(printf %q, "${VOWEL[@]}")
qCONS=$(printf %q, "${CONS[@]}")
eval "echo {${qVOWEL%,}}{${qCONS%,}}"
4
  • 2
    Just one more reason to use zsh.
    – Kevin
    Sep 16, 2013 at 22:08
  • Are you certain that there's no more direct way to do it in bash? Or do you just suspect that it is so?
    – Catskul
    Sep 16, 2013 at 22:09
  • @Catskul, no, I strongly doubt it but I'm not certain, I'm even less certain for ksh93 where a number of features are not documented. You may want to leave the question open for a while. I'm pretty sure you can't do it with brace expansion without another level of evaluation (with eval or .) though. Sep 16, 2013 at 22:14
  • eval "echo {$(printf ',%s' "${CONS[@]}" "${VOWEL[@]}" | tail -c+2)}" (Not working for single element though.)
    – Rockallite
    Feb 24, 2017 at 1:31
2

Fun, but probably not the best.

temparr=( b{a,e,i,o,u} c{a,e,i,o,u} d{a,e,i,o,u} )
echo "${temparr[@]}"
1
  • True, but requires repeating the vowels, which isn't implied from the question (assigning a static list to CONS and VOWEL each).
    – Jeff Schaller
    Aug 16, 2019 at 17:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .