How to get bash to automatically refresh program locations' cache?

2

1

I am aware of the bash internal command hash and how one can use hash -d or hash -r to forget remembered locations. Is there a way to instruct bash to automatically do this whenever it gets a "cache miss", i.e. when the remembered location goes away (no such file or directory) bash would clear the remembered location and try again?

Gerry Lufwansa

Posted 2014-03-26T10:25:28.443

Reputation: 67

Answers

6

You can achieve this with the checkhash option:

shopt -s checkhash

checkhash
    If set, bash checks that a command found in the hash table exists
    before trying to execute it.  If  a  hashed  command  no longer
    exists, a normal path search is performed.

You can make that the option for all bash shells by putting it into the BASHOPTS environment variable:

BASHOPTS
    A colon-separated list of enabled shell options.
    Each word in the list is a valid argument for the
    -s option to the shopt builtin command.

Setting this option may slightly slow down bash execution, since almost all of the time, the extra test is unnecessary. However, I wouldn't think that the cost of the test is significant.

rici

Posted 2014-03-26T10:25:28.443

Reputation: 3 493

1The cost of the test is relevant (each disk access == latency), but you are comparing that cost to the cost of searching the entire PATH for the file. Seems cheap for providing the feature the requester wanted. – Slartibartfast – 2014-03-27T05:55:27.983

1@slartibartfast: agreed. As I said, the cost is probably not significant. – rici – 2014-03-27T06:10:55.700

Thanks, this is exactly what I wanted. I wonder if there are Linux dists with this option set as the default? – Gerry Lufwansa – 2014-03-27T06:17:35.343

@GerryLufwansa: I doubt it, but it hardly seems like a deciding feature for a selecting a distro. It's just one line to add to your bash startup file (although figuring out which file can be a challenge with some distributions). – rici – 2014-03-27T18:50:45.123