Why is the command called which
and not where
?
Logically, you would want to search for the location of the executables, hence "where" are they, but not which.
Why is the command called which
and not where
?
Logically, you would want to search for the location of the executables, hence "where" are they, but not which.
This was mostly covered in comments, but this is my take on it.
The reason I have always understood it is that which
is showing you which binary is being called; there may be multiple binaries with the same name, but only one will be chosen when you run the command.
which
determines which of these binaries is being run by traversing the $PATH
environment variable:
[root@headdesk ~]# echo $PATH
/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
[root@headdesk ~]#
which
is going to look in /usr/local/sbin
, then /sbin
, and so on.
For example, look at which vim
, which is found in the 3rd position of our $PATH
:
[root@headdesk ~]# which vim
/bin/vim
If we add an executable with a higher path precedence, we will see the executable we added:
[root@headdesk ~]# >/usr/local/sbin/vim; chmod +x /usr/local/sbin/vim
[root@headdesk ~]# which vim
/usr/local/sbin/vim
If we want to see all vim
executables in our path, we can use the -a
flag:
[root@headdesk ~]# which -a vim
/bin/vim
/usr/bin/vim
This is covered more concisely in the man page:
DESCRIPTION
Which takes one or more arguments. For each of its arguments it prints to stdout the full path of the executables that would have been executed when this argument had been entered at the shell prompt. It does this by searching for an executable or script in the directories listed in the environment variable PATH using the same algorithm as bash(1).
The etymology is given in an early version of the which
program:
which : tells you which program you get
Only Bill Joy could tell you why the question was “which program do I get” rather than “where does the program come from” (but note that asking “where” ends up assuming there’s only one, when the purpose of which
was to determine which program would be used out of a potential set of programs).
Adding to the two excellent answers by cutrightjm and Stephen Kitt, there is a whereis
command which does what you say.
From its manpage:
whereis - locate the binary, source, and manual page files for a command
whence
command in Korn shells ;-). – Stephen Kitt Sep 30 '21 at 18:34which -a
. – Stephen Kitt Sep 30 '21 at 18:50which
makes perfect sense to me for the reasons outlined in the first comment - sure, I may want to know where a certain command is, but more importantly, I want to know which command is run if I typexyzzy
- since that name could exist in multiple locations in my PATH – Bravo Oct 01 '21 at 00:35