hash命令是bash的內置命令。緩存
咱們知道在bash中執行外部命令,會根據環境變量PATH來逐一搜索命令的路徑。bash
hash就是用於記住命令的路徑,而且在下次執行命令的時候直接經過hash獲取而再也不經過PATH一步步尋找,加快了尋找命令的速度。less
hash就像是命令的緩存。ui
hash [-lr] [-p pathname] [-dt] [name ...]
語法中的name就是每一個命令的名稱,例如:ls、grep、cat等。spa
當不使用任何選項和參數的時候,hash命令能夠輸出當前所記住的命令以及其緩存命中次數。code
一開始沒有執行外部命令的時候,hash是空的。blog
[root@C7 ~]# hash
hash: hash table empty
執行了幾個命令以後。若是某些命令有重複執行,那麼命中數會大於1。hash
[root@C7 ~]# hash hits command 1 /usr/bin/grep 1 /usr/bin/tail 1 /usr/bin/head 2 /usr/bin/ls
-d:刪除已記住的命令的路徑。it
[root@C7 ~]# hash hits command 1 /usr/bin/grep 1 /usr/bin/ls [root@C7 ~]# hash -d grep [root@C7 ~]# hash hits command 1 /usr/bin/ls
-l:也是輸出當前緩存中的內容,只不過輸出的格式可用於輸入或者再執行。table
[root@C7 ~]# hash -l builtin hash -p /usr/bin/ls ls
-p pathname:爲某個命令手動設置路徑。通常用於當命令的位置發生改變的狀況。若出現該狀況也能夠使用-d刪除緩存再從新執行一遍。
注意:若是指定了一個錯誤的路徑的話,那麼命令就沒法使用了,以下所示。
[root@C7 ~]# hash -p /tmp/grep grep [root@C7 ~]# hash hits command 0 /tmp/grep 0 /usr/bin/tail [root@C7 ~]# grep 'root' /etc/passwd -bash: /tmp/grep: No such file or directory
-r:清空緩存列表。
[root@C7 ~]# hash hits command 1 /usr/bin/sort 1 /usr/bin/cat 1 /usr/bin/ls [root@C7 ~]# hash -r [root@C7 ~]# hash hash: hash table empty
-t:顯示在緩存中,命令的對應路徑。命令不在緩存中則會報錯。
[root@C7 ~]# hash hits command 1 /usr/bin/head 1 /usr/bin/du 1 /usr/bin/cat 1 /usr/bin/less 1 /usr/bin/ls [root@C7 ~]# hash -t ls /usr/bin/ls [root@C7 ~]# hash -t less /usr/bin/less [root@C7 ~]# hash -t ls less grep ls /usr/bin/ls less /usr/bin/less -bash: hash: grep: not found
hash name:若是僅帶參數不帶選項的話,hash可用於清空具體命令的緩存命中次數。這個功能是不當心發現的,在「help hash」中並沒有說明。
[root@C7 ~]# hash hits command 1 /usr/bin/head 5 /usr/bin/wc [root@C7 ~]# hash wc [root@C7 ~]# hash hits command 1 /usr/bin/head 0 /usr/bin/wc