pwd 會以絕對路徑的形式印出當前工作目錄。它把從根目錄開始的完整路徑寫到標準輸出,各層目錄以 / 分隔,第一個 / 代表根目錄,最後一段就是當前所在目錄。
pwd [選項] -L, --logical 顯示當前目錄(保留連結路徑) -P, --physical 顯示實際的物理路徑 --help 說明 --version 版本資訊
一般情況下不加任何參數即可。
[root@localhost sunjimeng]# mkdir Documents [root@localhost sunjimeng]# cd / [root@localhost /]# cd /home/sunjimeng/Documents [root@localhost Documents]# pwd /home/sunjimeng/Documents
當目錄是透過軟連結進入時,pwd 顯示連結路徑,pwd -P 則顯示真實的物理路徑:
[sunjimeng@localhost mail]$ cd / [sunjimeng@localhost /]$ cd etc [sunjimeng@localhost etc]$ cd init.d [sunjimeng@localhost init.d]$ pwd /etc/init.d [sunjimeng@localhost init.d]$ pwd -P /etc/rc.d/init.d
[sunjimeng@localhost init.d]$ pwd -L /etc/init.d
PWD(1) User Commands PWD(1)
NAME
pwd - print name of current/working directory
SYNOPSIS
pwd [OPTION]...
DESCRIPTION
Print the full filename of the current working directory.
-L, --logical use PWD from environment, even if it contains symlinks
-P, --physical avoid all symlinks
--help display this help and exit
--version output version information and exit
[root@localhost init.d]# pwd -P /etc/rc.d/init.d [root@localhost init.d]# /bin/pwd /etc/rc.d/init.d [root@localhost init.d]# /bin/pwd -L /etc/init.d
如果 cd 是一層一層實走進去的,連結路徑與物理路徑就會一致,兩者也就沒有區別:
[root@localhost /]# cd etc/rc.d/init.d [root@localhost init.d]# pwd /etc/rc.d/init.d [root@localhost init.d]# pwd -P /etc/rc.d/init.d
把當前所在目錄刪掉之後,shell 內建的 pwd 仍然會印出那個已不存在的路徑,而 /bin/pwd 會直接報錯:
[root@localhost Documents]# mkdir removed [root@localhost Documents]# cd removed [root@localhost removed]# rmdir ../removed [root@localhost removed]# pwd /home/sunjimeng/Documents/removed [root@localhost removed]# /bin/pwd /bin/pwd: 在匹配的 inode ".." 上找不到目录入口
原因不難理解:內建 pwd 只是把環境變數 PWD 印出來,而 /bin/pwd 會真的去查 inode,因此能發現目錄已經消失。
在 Linux 裡,一個檔案對應唯一的一個 inode,但同一個 inode 可以有多個檔名指向它——這就是同一份實體檔案能透過不同路徑被訪問的原因。而 Linux 的哲學是「一切皆檔案」,目錄、新加的硬碟,都可以用處理檔案的方式對待。
連結分成兩類:硬連結(hard link)直接指向 inode;軟連結(symbolic link)又稱符號連結,本質上是一個記錄了目標路徑的特殊檔案,作用等同 Windows 的捷徑。這也解釋了為什麼刪掉捷徑指向的目錄後,透過軟連結進入時 pwd 與 /bin/pwd 會給出不同答案。
參考:https://www.linuxidc.com/Linux/2014-12/111056.htm