如何让bash自动刷新程序位置的缓存?

Ger*_*nsa 2 linux bash

我知道 bash 内部命令hash以及如何使用hash -dhash -r忘记记住的位置。有没有办法在bash“缓存未命中”时指示自动执行此操作,即当记住的位置消失时 ( no such file or directory)bash会清除记住的位置并重试?

ric*_*ici 6

您可以使用以下checkhash选项实现此目的:

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.
Run Code Online (Sandbox Code Playgroud)

您可以通过将其放入BASHOPTS环境变量来使其成为所有 bash shell 的选项:

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.
Run Code Online (Sandbox Code Playgroud)

设置此选项可能会稍微减慢 bash 的执行速度,因为几乎所有时间都不需要额外的测试。但是,我认为测试的成本并不高。