![$+commands[...] 中的 + 有何作用?](https://linux22.com/image/75441/%24%2Bcommands%5B...%5D%20%E4%B8%AD%E7%9A%84%20%2B%20%E6%9C%89%E4%BD%95%E4%BD%9C%E7%94%A8%EF%BC%9F.png)
这里还有一个无法搜索的问题:如何解释$+commands[foobar]
?我认为它是 的变体$commands[foobar]
,但谁知道呢。 (使用 zsh,至少我永远不知道。)
我还想知道如何在 zsh 文档中或在线搜索这个问题的答案。
答案1
这是记录在zsh 文档中的参数扩展部分:
${+name}
If name is the name of a set parameter ‘1’ is substituted, otherwise ‘0’
is substituted.
例子:
$ unset foo
$ if (( $+foo )); then echo set; else echo not set; fi
not set
$ foo=1
$ if (( $+foo )); then echo set; else echo not set; fi
set
在 中$+commands[foobar]
,zsh
检查返回的名称是否$commands[foobar]
为设置参数。
答案2
关于变量扩展的答案${+name}
基本上解决了问题。
我只是想添加一些有关速度比较的信息来完成该主题。使用 style 命令的原因(($+commands[tree]))
是,在数组中搜索命令比command -v tree
,更快which -a tree
。
❯ export TIMEFMT=$'%U user %S system %P cpu %*E total'
❯ time (for i ({1..100}) if (($+commands[tree])); then echo 1 &>/dev/null; fi)
0.00s user 0.00s system 89% cpu 0.006 total
❯ time (for i ({1..100}) if command -v tree &>/dev/null; then echo 1 &>/dev/null; fi)
0.00s user 0.00s system 95% cpu 0.010 total
❯ time (for i ({1..100}) if which -a tree &>/dev/null; then echo 1 &>/dev/null; fi)
0.01s user 0.01s system 97% cpu 0.021 total