Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand bash array into curly braces syntax

Tags:

bash

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
like image 998
Yuval Adam Avatar asked Dec 07 '14 18:12

Yuval Adam


People also ask

What are {} used for in bash?

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 "..".

How do you use the brace expansion in bash?

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.

What is curly bracket syntax?

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#.

What do {} do in Python?

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.


1 Answers

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")'
like image 162
gniourf_gniourf Avatar answered Oct 23 '22 07:10

gniourf_gniourf