While working on a macOS scripting problem recently I discovered that the behavior of which did not reflect the man page for which. There is a very good reason this. In zsh, which is a built-in shell command and the man page for which is for /usr/bin/which.
One can demonstrate which by running which which in either zsh or bash.
% zsh -c 'which which'
which: shell built-in command
% bash -c 'which which'
/usr/bin/which
The built-in command can be overridden with an alias:
% alias which=/usr/bin/which
Which which you wish to execute will depend on whichever needs you have in a given context.
What is which?
which locates a program in the user’s PATH environment variable. In other words, it answers the question of which executable will be run when a command is entered. For example, if I search on my system for “openssl” with the which executable I can find multiple answers in order:
% /usr/bin/which -a openssl
/usr/local/bin/openssl
/usr/bin/openssl
In zsh, which is defined as another built-in command: whence -c. The behavior of whence, and therefore which, is documented in man zshbuiltins.
I hope you enjoyed reading this post which was very fun to write.
Leave a comment