Shell

pwd 和 /bin/pwd 之間的奇怪區別

  • July 24, 2014

我在目前目錄中添加了一個符號連結ln -s . aa。如果我執行cd aa,然後我執行pwd,響應是/home/sim/aa.

但是如果我執行/bin/pwd它會列印/home/sim(目前目錄沒有改變)。

這種差異從何而來?

在包括 bash 在內的大多數 shell 中,pwd是一個內置的 shell:

$ type -a pwd
pwd is a shell builtin
pwd is /bin/pwd

如果使用/bin/pwd,則必須使用該-L選項來獲得與 builtin 相同的結果pwd

$ ln -s . test
$ cd test && pwd
/home/cuonglm/test
$ /bin/pwd
/home/cuonglm
$ /bin/pwd -L
/home/cuonglm/test

預設情況下,/bin/pwd忽略符號連結並列印實際目錄。

來自info pwd

`-L'
`--logical'
    If the contents of the environment variable `PWD' provide an
    absolute name of the current directory with no `.' or `..'
    components, but possibly with symbolic links, then output those
    contents.  Otherwise, fall back to default `-P' handling.

`-P'
`--physical'
    Print a fully resolved name for the current directory.  That is,
    all components of the printed name will be actual directory
    names--none will be symbolic links.

預設情況下,內置pwd包括符號連結,除了-P使用該選項或-o physical啟用 set builtin。

來自man bash

pwd [-LP]
             Print the absolute pathname of the  current  working  directory.
             The pathname printed contains no symbolic links if the -P option
             is supplied or the -o physical option to the set builtin command
             is  enabled.  If the -L option is used, the pathname printed may
             contain symbolic links.  The return status is 0 unless an  error
             occurs  while  reading  the  name of the current directory or an
             invalid option is supplied.

引用自:https://unix.stackexchange.com/questions/145479