What would be a nice way to take a bash array variable:
lst=(a b c)
and turn it into a curly brace syntax, such that it gives a statement equivalent to:
$ echo foo{a,b,c}
fooa foob fooc
? Naturally, I'm looking to replace the curly braces with the expansion of lst
. In my specific case, it is not possible (or rather, extremely ugly) to use a for
loop.
Closest I got so far is:
$ lst=(a b c); echo foo${lst[@]}
fooa b c
Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specification or a comma separated list of items inside curly braces "{}". A sequence consists of a starting and ending item separated by two periods "..".
A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged. A { or ' , ' may be quoted with a backslash to prevent its being considered part of a brace expression.
Noun. curly-bracket language (plural curly-bracket languages) (programming) A programming language whose syntax uses curly brackets to enclose blocks, such as C, C++, Java, or C#.
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.
Recall that if ary
is an array, then the expansion of ${ary[@]/#/foo}
is that of ary
, with foo
prepended to each field. Similarly, ${ary[@]/%/foo}
appends foo
to each field. Look:
$ lst=( a b c )
$ echo "${lst[@]/#/foo}"
fooa foob fooc
$ echo "${lst[@]/%/foo}"
afoo bfoo cfoo
You don't need eval
or printf
for that.
Like so, you can safely build arrays:
$ lst=( a 'field with space' b )
$ foolst=( "${lst[@]/#/foo}" )
$ declare -p foolst
declare -a foolst='([0]="fooa" [1]="foofield with space" [2]="foob")'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With