Apply parameter expansion flags to string or array literal in zsh

zsh

Sometimes I'd like to apply parameter expansion flags to a string or array literal in zsh. As an example use case, say that I want to split some comma-delimited string $arglist on commas, but prepend something to the front. It would be nice to be able to do this:

${(s/,/)arg1,arg2,$restofarglist}

Of course there are other ways to solve this particular problem, and I know that I can always assign to a parameter first and then apply the flags. But the question is: can I apply flags directly to a literal somehow?

Best Answer

I think you are looking for :- parameter substitution:

$ restofarglist='abc,def'
$ echo ${(s/,/)${:-arg1,arg2,$restofarglist}}
arg1 arg2 abc def

From man zsh:

${name:-word}
              If name is set, or in the second form is non-null, then substitute its value;
              otherwise substitute word.  In the second form name may be omitted, in  which
              case word is always substituted.

Actually you can make this example a little bit shorter:

$ echo ${${:-arg1,arg2,$restofarglist}//,/ }
arg1 arg2 abc def
Related Question