3

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
4

You can use parameter expansion

$ arr=(a b c)

$ echo "${arr[@]/#/foo.}"
foo.a foo.b foo.c
5
  • 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 7:57
  • or "${arr[@]/+()/foo.}", or "${arr[@]/?()/foo.}" in ksh/bash, but all will fail in zsh. @StéphaneChazelas – Isaac 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. – Isaac 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
1
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.