In case of shell-builtins (eg type
itself):
$ type type
type is a shell builtin
$ which type
<Doesn't return anything since it's a shell builtin, silently exits>
In case of commands (normally) (eg python
):
$ type python
python is /usr/bin/python
$ which python
/usr/bin/python
In case of which
(which is a command located at /usr/bin/which
)
$ type which
which is hashed (/usr/bin/which)
$ which which
/usr/bin/which
Why does type which
say that which is hashed
? What is the significance of which
being hashed and what does it actually mean?
You likely have a long PATH set and, to find an executable, the shell needs to search the path. To avoid that time consuming process every time that you want to run a program, the shell may keep a list of programs that it has already found. That list is called a "hash." When the shell says that
which
is hashed, it means that it has already done the PATH search and foundwhich
and saved its location in the hash.man bash
explains it as follows:While the hash normally speeds up shell operations, there is one case where it causes problems. If you update your system and, as a result, some executable moves to a new location, the shell may get confused. The solution is to run
hash -r
which causes the shell to forget all the hashed locations and search the PATH from scratch.Why are some executables missing from the hash?
An executable is not placed in the hash until after you execute at least once. Observe:
python
is hashed only after it has been executed.How to examine what is in bash's hash
The contents of the hash are available in the
bash
arrayBASH_CMDS
. You can see what is in it with the commanddeclare -p BASH_CMDS
. When a new shell or subshell is opened, the hash is empty. Commands are added one by one as they are used. From a newly opened shell, observe: