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
1

2 Answers 2

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). Commented Jul 16, 2020 at 7:57
  • or "${arr[@]/+()/foo.}", or "${arr[@]/?()/foo.}" in ksh/bash, but all will fail in zsh. @StéphaneChazelas Commented Jul 18, 2020 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. Commented Jul 18, 2020 at 20:07
  • @StéphaneChazelas The point is still valid: there is no portable solution. Commented Jul 18, 2020 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. Commented Jul 20, 2020 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 :/ Commented Jul 20, 2020 at 13:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.