`hash -r 2` 是做什么的?

What does `hash -r 2` do?

我在 virtualenv activate 文件中找到这段代码:

# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands.  Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then
    hash -r 2>/dev/null
fi

hash -r 2 在 bash 和 zsh 中都给我一个错误。这段代码是如何工作的?这段代码如何忘记过去的命令? 如果我们不忘记过去的命令,为什么 $PATH 更改可能得不到尊重?你能举个例子吗?

命令不是

hash -r 2

而是

hash -r

2standard error redirect/dev/null 的一部分,它基本上丢弃了错误输出。

您可以阅读 man bash 中内置 hash 的 Bash 版本。这是一个相关的片段:

Any previously-remembered pathname is discarded. If the -p option is supplied, no path search is performed, and filename is used as the full filename of the command. The -r option causes the shell to forget all remembered locations.