
時々、zsh の文字列または配列リテラルにパラメータ拡張フラグを適用したいことがあります。使用例の 1 つとして、カンマ$arglist
で区切られた文字列をカンマで分割し、先頭に何かを追加したいとします。次のようにできれば便利です。
${(s/,/)arg1,arg2,$restofarglist}
もちろん、この特定の問題を解決する方法は他にもあり、最初にパラメータに割り当ててからフラグを適用できることはわかっています。しかし、問題は、何らかの方法でリテラルにフラグを直接適用できるかどうかです。
答え1
:-
パラメータ置換を探しているのだと思います:
$ restofarglist='abc,def'
$ echo ${(s/,/)${:-arg1,arg2,$restofarglist}}
arg1 arg2 abc def
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.
実際には、この例をもう少し短くすることができます。
$ echo ${${:-arg1,arg2,$restofarglist}//,/ }
arg1 arg2 abc def