Expand bash array into curly braces
What would be a good way to accept a bash array variable:
lst=(a b c)
and turn it into curly brace syntax so that it gives a statement equivalent to:
$ echo foo{a,b,c}
fooa foob fooc
? Naturally, I want to replace the curly braces with an extension lst
. In my particular case, it is impossible (more precisely, extremely ugly) to use a loop for
.
The closest I am so far is:
$ lst=(a b c); echo foo${lst[@]}
fooa b c
source to share
Recall that if it ary
is an array, then the extension ${ary[@]/#/foo}
matches the extension ary
, and is foo
appended to each field. Likewise, ${ary[@]/%/foo}
adds foo
to each field. Take a look:
$ lst=( a b c )
$ echo "${lst[@]/#/foo}"
fooa foob fooc
$ echo "${lst[@]/%/foo}"
afoo bfoo cfoo
You don't need eval
or for this printf
.
This way you can create arrays safely:
$ lst=( a 'field with space' b )
$ foolst=( "${lst[@]/#/foo}" )
$ declare -p foolst
declare -a foolst='([0]="fooa" [1]="foofield with space" [2]="foob")'
source to share