4

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?

6

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
  • For me (zsh 5.0.5) your first example only works if I put double quotes around the parameter: echo ${(s/,/)${:-"arg1,arg2,$restofarglist"}}. Without them I get "arg1,arg2,abc def" as output. – Adaephon Oct 7 '14 at 7:27
  • @Adaephon same here (v 5.0.6); anyone understand why? – Sean Mackesey Oct 7 '14 at 8:07
  • What does setopt return? – jimmij Oct 7 '14 at 12:25
  • alwaystoend autocd autonamedirs autopushd autoresume nobgnice braceccl nocaseglob cdablevars nocheckjobs noclobber combiningchars completeinword correct extendedglob extendedhistory noflowcontrol globassign histexpiredupsfirst histfindnodups histignorealldups histignoredups histignorespace histsavenodups histverify nohup incappendhistory interactive login longlistjobs nonomatch pathdirs promptsubst pushdignoredups pushdsilent pushdtohome rcquotes sharehistory shinstdin – Sean Mackesey Oct 7 '14 at 16:23
  • unsetopt braceccl and it should work without quotes as well. – jimmij Oct 7 '14 at 16:33

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.