What's the difference between `whereis` and `which`

133 阅读1分钟

There are two familar commands to return the command path: whereis and which. But sometimes the result of them are different. For example, to check the node path: image

So, what's the difference between whereis and which?

In the man page of whereis, it clearly says:

The whereis utility checks the standard binary directories for the specified programs, printing out the paths of any it finds. The path searched is the string returned by the sysctl(8) utility for the 'user.cs_path' string.

And the user.cs_path retrieved by sysctl is /usr/bin:/bin:/usr/sbin:/sbin. These paths are the standard binary directories.

From the tldr page of which (This page is more approachable than the man page), it clearly says:

Search the PATH environment variable and display the location of any matching executables:
which executable

So it will return the paths regardless of whether standard binary paths.

Note: In order to show all the matched paths, the -a option must be used.

➜  ~ which git
/usr/bin/git
➜  ~ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
➜  ~ which -a git
/usr/local/bin/git
/usr/bin/git

Note: In zsh, where is a shell builtin command which is equivalent to which -a.

Conclusion

Typically, it's better to use which than whereis.