4

In Bash we can already do this:

echo foo.{a,b,c}
# == foo.a foo.b foo.c

How do we get roughly:

arr=(a b c)
echo foo.{${arr[@]}}
# == foo.a foo.b foo.c
Mussri
  • 141
  • 3

2 Answers2

4

You can use parameter expansion

$ arr=(a b c)

$ echo "${arr[@]/#/foo.}" foo.a foo.b foo.c

steeldriver
  • 81,074
  • or "${arr[@]/@()/foo.}" (with extglob) which would make it also work in ksh93 (where the ${param/pattern/replacement} operator comes from). – Stéphane Chazelas Jul 16 '20 at 07:57
  • or "${arr[@]/+()/foo.}", or "${arr[@]/?()/foo.}" in ksh/bash, but all will fail in zsh. @StéphaneChazelas –  Jul 18 '20 at 18:51
  • @Isaac, @(x), +(x) and ?(x) are ksh glob operators whose zsh equivalents are (x), x## and (x|). To use those ksh glob operators in zsh, you'd set the kshglob option, though you'd probably only do that as part of the ksh emulation to interpret code intended for ksh. – Stéphane Chazelas Jul 18 '20 at 20:07
  • @StéphaneChazelas The point is still valid: there is no portable solution. –  Jul 18 '20 at 20:25
  • This works, though I don't suppose it can be pushed all the way. Seems I can do it only once per expression, and it's either prefix or suffix. Otherwise I'd have to invent and maintain "names" for the locations I want to expand each array in and substitute those. – Mussri Jul 20 '20 at 13:15
3

In case you don't have to use bash:

rc/es/akanga

(that's the default behaviour):

$ arr=(a b c)
$ echo foo.$arr
foo.a foo.b foo.c

zsh:

$ arr=(a b c)
$ echo foo.$^arr
foo.a foo.b foo.c

Or

$ set -o rcexpandparam
$ arr=(a b c)
$ echo foo.$arr
foo.a foo.b foo.c

(^ enables rcexpandparam for that one expansion, like = enables shwordsplit, or ~ globsubst)

fish

(also the default behaviour)

$ set arr a b c
$ echo foo.$arr
foo.a foo.b foo.c

All those shells have a better array design than bash's (itself copied from ksh)).

Note that zsh and fish expansion works like brace expansion. In rc, it differs when using echo $arr.$arr, which gives:

a.a b.b c.c

while in fish/zsh -o rcexpandparam, it gives the same as echo {a,b,c}.{a,b,c}, that is:

a.a a.b a.c b.a b.b b.c c.a c.b c.c
  • I wish I could somehow do away with Bash. But probably no shell alternative will do. It'd be easier to port to Python as that's already guaranteed to be installed. But it makes some very common pipelining too cumbersome :/ – Mussri Jul 20 '20 at 13:12