The main purpose is to determine whether a command exists in PATH
.
Some of the following methods also support determine the existence
of function
s. The comparison focuses on speed, not support coverage.
❯ 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 hash tree &>/dev/null; then echo 1 &>/dev/null; fi)
0.00s user 0.00s system 92% cpu 0.007 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 whence -p tree &>/dev/null; then echo 1 &>/dev/null; fi)
0.00s user 0.01s system 94% cpu 0.010 total
❯ time (for i ({1..100}) if type tree &>/dev/null; then echo 1 &>/dev/null; fi)
0.01s user 0.01s system 97% cpu 0.019 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
Note: which
is a builtin in ZSH, not the external command /usr/bin/which
.
What does the + do in $+commands[…]?
${+name}
If name is the name of a set parameter ‘1’ is substituted, otherwise ‘0’ is substituted.