“rm被散列”是什么意思?

63 shell bash command

我正在浏览http://mywiki.wooledge.org/BashGuide/CommandsAndArguments并遇到了这个:

$ type rm
rm is hashed (/bin/rm)
$ type cd
cd is a shell builtin
Run Code Online (Sandbox Code Playgroud)

早些时候,该指南列出了 Bash 可以理解的各种类型的命令:别名、函数、内置函数、关键字和可执行文件。但没有提到“散列”。那么,在这种情况下,“散列”是什么意思?

fro*_*utz 65

这是一个性能问题;不是每次调用时都搜索整个路径以查找二进制文件,而是将其放入哈希表中以便更快地查找。所以任何已经在这个哈希表中的二进制文件都会被哈希。如果你在二进制文件已经散列后移动它们,它仍然会尝试在它们的旧位置调用它们。

另请参阅help hash, 或man bashhash在那里搜索下内置命令。


slm*_*slm 16

正如其他人提到的,哈希是 Bash 维护的关联数组(键 --> 值),因此当执行命令时,Bash 首先搜索此哈希以查看是否已通过 找到命令在磁盘上的位置$PATH,并将其存储在那里以便更快地搜索。

您可以通过提供您希望 Bash 在调用时找到的命令列表来预加载哈希。这个变量被称为BASH_CMDS

摘自手册页

   BASH_CMDS
          An  associative  array  variable  whose members correspond to the 
          internal hash table of commands as maintained by the hash builtin.
          Elements added to this array appear in the hash table; unsetting 
          array elements cause commands to be removed from the hash table.
Run Code Online (Sandbox Code Playgroud)

此外,如果您查看 Bash 手册页,有一个标题为COMMAND EXECUTION的部分,其中详细说明了在提示符下键入命令时 Bash 使用的状态机。

摘抄

   If the name is neither a shell function nor a builtin, and contains no 
   slashes, bash searches each element of the PATH for a directory con?
   taining an executable file by that name.  Bash uses a hash table to 
   remember the full pathnames of executable files (see hash  under  SHELL
   BUILTIN COMMANDS below).  A full search of the directories in PATH is 
   performed only if the command is not found in the hash table.  If the
   search is unsuccessful, the shell searches for a defined shell function 
   named command_not_found_handle.  If that  function  exists,  it  is
   invoked  with  the  original command and the original command's arguments 
   as its arguments, and the function's exit status becomes the exit
   status of the shell.  If that function is not defined, the shell prints 
   an error message and returns an exit status of 127.
Run Code Online (Sandbox Code Playgroud)

您可以使用-l开关找出当前哈希中的内容。

例子

$ hash -l
builtin hash -p /usr/bin/rm rm
builtin hash -p /usr/bin/sudo sudo
builtin hash -p /usr/bin/man man
builtin hash -p /usr/bin/ls ls
Run Code Online (Sandbox Code Playgroud)

  • 非常有帮助,谢谢。当我正在编写脚本时,我发现这个哈希问题妨碍了我。有没有办法禁用或清除它? (2认同)
  • `hash -r` 将清除整个散列(对于所有散列命令)。这记录在“man bash”中 (2认同)

Rub*_*vvy 10

hash 是一个内置的 Bash shell,为命令提供散列。

hash [-lr] [-p filename] [-dt] [name]
Run Code Online (Sandbox Code Playgroud)

直接从马嘴里说出来:

help hash

记住或显示程序位置。

info Bash? Shell 内置命令 ? Bourne Shell 内置函数

记住指定为 NAME 参数的命令的完整路径名,因此无需在后续调用中搜索它们。这些命令是通过搜索 中列出的目录找到的$PATH。该-p选项禁止路径搜索,FILENAME 用作 NAME 的位置。该-r选项会导致外壳忘记所有记住的位置。该-d选项会导致 shell 忘记每个 NAME 的记住位置。如果-t提供了该选项,则打印每个 NAME 对应的完整路径名。如果多个 NAME 参数与 NAME 一起提供,-t则在散列的完整路径名之前打印。该-l选项使输出以可重复用作输入的格式显示。如果没有给出参数,或者如果只有-l提供,打印有关记住的命令的信息。除非未找到 NAME 或提供了无效选项,否则返回状态为零。