將參數擴充標誌套用至 zsh 中的字串或陣列文字

將參數擴充標誌套用至 zsh 中的字串或陣列文字

有時我想將參數擴展標誌應用於 zsh 中的字串或陣列文字。作為一個範例用例,假設我想用$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

相關內容