When to rehash executables in $PATH with bash?

9

Bash shell has a built-in command hash -r to reset the internal $PATH cache for executables.

When is it necessary to use this command?

Related: How to rehash executables in $PATH with bash

kevinarpe

Posted 2015-11-12T07:32:47.890

Reputation: 2 133

1...for example when you have a program that you just recompiled... with the same name...maybe in a different path... – Hastur – 2015-11-12T08:06:00.610

@Hastur: I'm unsure if you comment is a question or a statement. If statement, pls post as an answer. – kevinarpe – 2015-11-12T08:09:54.507

Answers

7

hash is a bash built-in command. The hash table is a feature of bash that prevents it from having to search $PATH every time you type a command by caching the results in memory.

So when the cached/stored information are not anymore updated or valid you may need to reset it.

Read more on this nice answer on Unix stackexchange.

Hastur

Posted 2015-11-12T07:32:47.890

Reputation: 15 043

4

If you've previously run a program in that shell invocation, and then install another version of it in an earlier directory in your $PATH search list, you need to reset the hash so it will find it in the new location. Otherwise, it will use the cache to find the program in the old location.

You also need to reset the hash if a program is installed in 2 directories in your $PATH, and you remove the copy from the earlier location after having run it. Otherwise, it will try to find it in that location, and report "No such file or directory" (personally, I think it should automatically clear the hash and do a full search when that happens, but it didn't happen when I tried).

Note that you don't actually have to reset the entire hash, you can use:

hash name

to force it to update the cache entry for just that name, or:

hash -d name

to delete just that cache entry. These leave all other cache entries alone.

You don't need to use hash -r after modifying $PATH, it's reset automatically when this is done.

Barmar

Posted 2015-11-12T07:32:47.890

Reputation: 1 913

Good point about the install part and the point in your path. – kevinarpe – 2015-11-19T05:57:16.330