请注意,这是不是重复的。我问的是禁用缓存,而不是清除它。如果您有缓存需要清除,那么它显然没有被禁用。
在极少数情况下,我注意到 bash 缓存了它在路径中找到的东西,这不是因为它有帮助,而是因为它非常烦人。一个例子:
~ dc$ export PATH=$HOME/bin:$PATH
~ dc$ cat bin/which
#!/bin/bash
echo "my which"
~ dc$ which
my which
~ dc$ rm bin/which
~ dc$ which which
-bash: /Users/dc/bin/which: No such file or directory
在另一个壳里...
~ dc$ which which
/usr/bin/which
我确信这种缓存在过去的美好时光是有意义的,当时磁盘速度很慢,内存昂贵且有限,因此您无法缓存太多 - 缓存路径比缓存查找命令所需的所有磁盘块更便宜。但如今它并没有提供任何明显的好处,而且造成的问题比它解决的问题还要多。这是一个错误,几乎是一个错误。
我什至找不到禁用它的方法。有什么指点吗?
答案1
您可以在绘制提示之前清除散列的可执行文件:
PROMPT_COMMAND='hash -r'
从help hash
:
hash: hash [-lr] [-p pathname] [-dt] [name ...]
Remember or display program locations.
Determine and remember the full pathname of each command NAME. If
no arguments are given, information about remembered commands is displayed.
Options:
-d forget the remembered location of each NAME
-l display in a format that may be reused as input
-p pathname use PATHNAME is the full pathname of NAME
-r forget all remembered locations
-t print the remembered location of each NAME, preceding
each location with the corresponding NAME if multiple
NAMEs are given
Arguments:
NAME Each NAME is searched for in $PATH and added to the list
of remembered commands.
Exit Status:
Returns success unless NAME is not found or an invalid option is given.
答案2
如果哈希表中的命令不再存在,您可以强制 bash 执行新的路径查找。
shopt -s checkhash
来自 bash 的联机帮助页:
检查哈希值
如果设置,巴什在尝试执行之前检查哈希表中找到的命令是否存在。如果散列命令不再存在,则执行正常路径搜索。
例子:
[blabla]$ PATH=$HOME/bin:$PATH
[blabla]$ hash -r
[blabla]$ cat bin/which
#!/bin/bash
echo "my which"
[blabla]$
[blabla]$ shopt -s checkhash
[blabla]$ which
my which
[blabla]$ mv bin/which bin/dis.which
[blabla]$ which which
/usr/bin/which