hash命令用来显示和清除哈希表,执行命令的时候,系统将先查询哈希表。

简介

linux系统下会有一个hash表,当你刚开机时这个hash表为空,每当你执行过一条命令时,hash表会记录下这条命令的路径,就相当于缓存一样。第一次执行命令 shell解释器默认的会从 PATH 路径 下寻找该命令的路径,当你第二次使用该命令时,shell解释器首先会查看hash表,没有该命令才会去PATH路径下寻找, 大大提高命令的调用速率。

语法格式

hash [-lr] [-p pathname] [-dt] [name …]

常用参数

-d NAME 在哈希表中清除 NAME 这条记录
-l 显示哈希表中的命令
-p <指令> 将具有完整路径的命令加入到哈希表中
-r 清除哈希表中的全部记录
-t NAME 输出 hash 表中的 NAME 的路径

示例

  1. [root@gkdaxue ~]# hash
  2. hash: hash table empty
  3. [root@gkdaxue ~]# echo 'test' > test.txt
  4. [root@gkdaxue ~]# cat test.txt
  5. test
  6. [root@gkdaxue ~]# ls
  7. [root@gkdaxue ~]# hash -l
  8. builtin hash -p /usr/bin/cat cat
  9. builtin hash -p /usr/bin/ls ls
  10. ## -t 参数
  11. [root@gkdaxue ~]# hash -t cat
  12. /usr/bin/cat
  13. [root@gkdaxue ~]# hash -t fdisk
  14. -bash: hash: fdisk: not found
  15. ## -d
  16. [root@gkdaxue ~]# hash
  17. hits command
  18. 3 /usr/bin/cat
  19. 2 /usr/bin/ls
  20. [root@gkdaxue ~]# hash -d cat
  21. [root@gkdaxue ~]# hash
  22. hits command
  23. 2 /usr/bin/ls
  24. ## -r 全部清除
  25. [root@gkdaxue ~]# hash -r
  26. [root@gkdaxue ~]# hash
  27. hash: hash table empty
  28. ## -p 参数
  29. [root@gkdaxue ~]# hash -p /usr/bin/cat cat
  30. [root@gkdaxue ~]# hash
  31. hits command
  32. 0 /usr/bin/cat

证明是从 PATH 变量中搜索

  1. [root@localhost ~]# hash
  2. hits command
  3. 1 /usr/bin/cat ## 之前的路径
  4. [root@localhost ~]# echo $PATH
  5. /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
  6. [root@localhost ~]# mv /usr/bin/cat /usr/local/bin/
  7. [root@localhost ~]# cat test.txt
  8. -bash: /usr/bin/cat: No such file or directory
  9. [root@localhost ~]# hash -r
  10. [root@localhost ~]# cat test.txt
  11. test
  12. [root@localhost ~]# hash
  13. hits command
  14. 1 /usr/local/bin/cat ## 移动后的路径
  15. [root@localhost ~]# mv /usr/local/bin/cat /usr/bin/
  16. [root@localhost ~]# cat test.txt
  17. -bash: /usr/local/bin/cat: No such file or directory
  18. [root@localhost ~]# hash -r