有时我想将参数扩展标志应用于 zsh 中的字符串或数组文字。作为示例用例,假设我想在逗号上拆分一些逗号分隔的字符串$arglist
,但在前面添加一些内容。能够做到这一点会很好:
${(s/,/)arg1,arg2,$restofarglist}
Run Code Online (Sandbox Code Playgroud)
当然,还有其他方法可以解决这个特定问题,我知道我总是可以先分配给参数,然后再应用标志。但问题是:我可以以某种方式将标志直接应用于文字吗?
我认为您正在寻找:-
参数替换:
$ restofarglist='abc,def'
$ echo ${(s/,/)${:-arg1,arg2,$restofarglist}}
arg1 arg2 abc def
Run Code Online (Sandbox Code Playgroud)
来自 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.
Run Code Online (Sandbox Code Playgroud)
其实你可以把这个例子缩短一点:
$ echo ${${:-arg1,arg2,$restofarglist}//,/ }
arg1 arg2 abc def
Run Code Online (Sandbox Code Playgroud)