Skip to content

Instantly share code, notes, and snippets.

@laggardkernel
Last active October 16, 2019 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laggardkernel/6f5d333657615ad2926e3ea0dd6e0294 to your computer and use it in GitHub Desktop.
Save laggardkernel/6f5d333657615ad2926e3ea0dd6e0294 to your computer and use it in GitHub Desktop.
determine whether a command exists in zsh

Determine Whether a Command Exists in ZSH

The main purpose is to determine whether a command exists in PATH. Some of the following methods also support determine the existence of functions. 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.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment