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[@]}}
Catskul
  • 1,898
  • 1
  • 14
  • 19
  • 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 .. ` – Rahul Patil Sep 16 '13 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 '13 at 21:20

3 Answers3

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
Lri
  • 5,143
  • 2
  • 27
  • 20
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%,}}"
terdon
  • 234,489
  • 66
  • 447
  • 667
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • 2
    Just one more reason to use zsh. – Kevin Sep 16 '13 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 '13 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. – Stéphane Chazelas Sep 16 '13 at 22:14
  • `eval "echo {$(printf ',%s' "${CONS[@]}" "${VOWEL[@]}" | tail -c+2)}"` (Not working for single element though.) – Rockallite Feb 24 '17 at 01: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[@]}"
D.Fitz
  • 121
  • 4
  • 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 '19 at 17:14