更新Bash路径的缓存

---恢复内容开始---

1、登陆一个新的vps时候,发现git的版本是1.8的,太久了,于是就源码安装了新的版本2.4。

2、老版本在/usr/bin/git,新版本安装的/usr/local/bin/git

3、问题来了,安装完新的后,卸载了旧的版本,在运行git --version时,却提示如下错误:

-bash: /usr/bin/git: No such file or directory

4、我去,bash只搜索旧的路径,查看了一下PATH变量:

[root@noi bin]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

没有问题,而且/usr/local/bin还在前面,但系统却不搜索,我晕,这是啥问题?

5、经过一番折腾,终于找到答案,原来Bash路径也是有缓存地,只要运行过的命令,bash就会保存到一张hash表里,下次直接从hash表里找地址,就不按个路径找了。

6、运行:help hash查看一下:

[root@noi bin]# 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.

7、在运行hash命令,查看hash表里都有啥?

[root@noi bin]# hash
hits    command
   5    /usr/bin/git
   1    /usr/sbin/ifconfig
   1    /usr/bin/rm
   7    /usr/bin/vim
   1    /usr/bin/wget
   1    /usr/bin/mv
  19    /usr/bin/yum
   1    /usr/bin/ln
   1    /usr/bin/man
   5    /usr/bin/make
   1    /usr/bin/tar
  15    /usr/bin/ls

果然,第一个就是git,而且地址还是老地址。

8、运行: hash -d git 删除掉git的缓存。

9、再次执行git --version 哈哈,正确显示了新安装的版本。

---恢复内容结束---

原文地址:https://www.cnblogs.com/litifeng/p/7672784.html