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 的路径 |
示例
[root@gkdaxue ~]# hashhash: hash table empty[root@gkdaxue ~]# echo 'test' > test.txt[root@gkdaxue ~]# cat test.txttest[root@gkdaxue ~]# ls[root@gkdaxue ~]# hash -lbuiltin hash -p /usr/bin/cat catbuiltin hash -p /usr/bin/ls ls## -t 参数[root@gkdaxue ~]# hash -t cat/usr/bin/cat[root@gkdaxue ~]# hash -t fdisk-bash: hash: fdisk: not found## -d[root@gkdaxue ~]# hashhits command3 /usr/bin/cat2 /usr/bin/ls[root@gkdaxue ~]# hash -d cat[root@gkdaxue ~]# hashhits command2 /usr/bin/ls## -r 全部清除[root@gkdaxue ~]# hash -r[root@gkdaxue ~]# hashhash: hash table empty## -p 参数[root@gkdaxue ~]# hash -p /usr/bin/cat cat[root@gkdaxue ~]# hashhits command0 /usr/bin/cat
证明是从 PATH 变量中搜索
[root@localhost ~]# hashhits command1 /usr/bin/cat ## 之前的路径[root@localhost ~]# echo $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin[root@localhost ~]# mv /usr/bin/cat /usr/local/bin/[root@localhost ~]# cat test.txt-bash: /usr/bin/cat: No such file or directory[root@localhost ~]# hash -r[root@localhost ~]# cat test.txttest[root@localhost ~]# hashhits command1 /usr/local/bin/cat ## 移动后的路径[root@localhost ~]# mv /usr/local/bin/cat /usr/bin/[root@localhost ~]# cat test.txt-bash: /usr/local/bin/cat: No such file or directory[root@localhost ~]# hash -r
