2

I am trying to do the following without an intermediate variable:

list_a=(a b c)         # build a list
list_b=(1${^list_a})   # 1a 1b 1c
joined=${(j:,:)list_b} # 1a,1b,1c

I would expect something like this work...

${(j:,:)(1${^(a b c)})}

Then I realized that my core assumptions was just wrong...

1${^(a b c)} # this gives a bad substitution error

I am pretty sure I fundamentally don't understand how nested array substitution works in zsh...

0

1 Answer 1

3

You cannot use an array declaration inside a parameter substitution. And even if it did work, it would be mainly an overly complicated way to build the string "1a,1b,1c".

If you really need this for some reason, you can go with

echo ${(j:,:):-1${^${=:-a b c}}}

Explanation:

  • ${:-a b c} is substituted with "a b c". This way a string can be injected like it would be from a parameter substiton. This may seem like a null-operation, but it is needed for the next step.
  • ${=spec} performs word splitting during the evaluation of spec. This requires spec to be a parameter name or parameter substitution. In this case ${=:-a b c} is split into the array (a b c)
  • ${^spec} allows for expansions like foo${^list}barfooabar foobbar foocbar instead of foo${list}barfooa b cbar. (with list=(a b c))
  • ${(j:,:)array} joins the elements of array with , as separator. This again requires array to be an parameter name or parameter expansion. As the previous expansion is combined with the string 1, it needs to be inserted with a ${:-word} substitution.

As I said initially, this is little more than a complex way to say "1a,1b,1c". In my opinion it would only make sense, if the array is already declared outside of the substitution. In which case you can just replace the ${=:-a b c} part with the name of the array parameter:

list=(a b c)
echo ${(j:,:):-1${^list}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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