When you enter a command, if there were no hash table, the shell would check every directory listed in the $PATH
variable to see if your command is found there.
This can be a slow process if any of those directories is attached to a slow device. You would get a pause every time you enter a command.
So, when the shell starts running, it reads every directory in the $PATH
and determines what all the executable programs are, then stores this list into a hash table in memory. Then, it never needs to check them again, and it can quickly know if a command you typed is valid or not.
This works great as long as you never add or remove programs, because as soon as you do, the hash table is going to be out of date. The purpose of the rehash
command is to ask the shell to go and read the list of programs again.
The above applies to csh
and tcsh
.
With the bash
shell, it does not read in the names of all your programs at startup. It does keep a hash table, but it only puts things in it as you type commands. For example:
bash-3.2$ ls
foo bar baz
bash-3.2$ cp
cp: missing file operand
Try `cp --help' for more information.
bash-3.2$ hash
hits command
1 /bin/cp
1 /bin/ls
It has remembered the locations of the cp
and ls
commands.