2017-07-24 76 views
1

我发现这个在prezto源代码:zsh的神秘变量扩展

# Set the command name, or in the case of sudo or ssh, the next command. 
local cmd="${${2[(wr)^(*=*|sudo|ssh|-*)]}:t}" 

我一直在读zsh doc了很多,但还是一无所获靠近这是怎么回事。在shell本身的实验中,它似乎表明[]是一些算术的东西,这很有道理,但我没有看到解释(w)应该如何工作的部分。这似乎是一个适用于数学表达式一些神奇的运营商......

[email protected] ~/.zprezto ❯❯❯ VAR="one two three four" 
[email protected] ~/.zprezto ❯❯❯ echo ${VAR[2]} 
n 
[email protected] ~/.zprezto ❯❯❯ echo ${VAR[(w)2]} 
two 
[email protected] ~/.zprezto ❯❯❯ echo ${VAR[(w)]} 
zsh: bad math expression: empty string 
[email protected] ~/.zprezto ❯❯❯ 
+0

http://zsh.sourceforge.net/Doc/Release/Parameters.html#Array-Subscripts – melpomene

+0

http://zsh.sourceforge.net/Doc/Release/Parameters.html#Subscript-Flags – melpomene

回答

2

它乍看上去相当混乱,但一旦你打破它到它的部分是相当简单的。这是ZSH中参数扩展和扩展通配支持的一个例子。如果你看看higher up in the function从该代码示例是,你会看到他们设置:

emulate -L zsh 
setopt EXTENDED_GLOB 

现在让我们掰开行,你必须有:

${ 
    ${ 
    2[ # Expand the 2nd argument 
     (wr) # Match a word 
     ^(*=*|=|sudo|ssh|-*) # Do not match *=*, =, sudo, ssh, or -* 
    ] 
    } 
:t} # If it is a path, return only the filename 

您可以通过测试这个创建这样一个示例脚本:

#!/bin/zsh 

emulate -L zsh 
setopt EXTENDED_GLOB 

echo "${$1[(wr)^(*=*|sudo|ssh|-*)]}:t}" # changed 2 to 1, otherwise identical 

下面就是它输出:

$ ./test.sh '/bin/zsh' 
zsh 

$ ./test.sh 'sudo test' 
test 

$ ./test.sh 'sudo --flag test' 
test 

$ ./test.sh 'ssh -o=value test' 
test 

$ ./test.sh 'test' 
test 

欲了解更多信息,请参阅the documentation on expansioncsh-style modifiers

+0

我猜主要的缺点是难以从第15条提起第15条谷歌的结果 –