pwd和$ PWD之间的使用差异


9

要打印当前/当前工作目录,可以使用环境变量 $PWD命令 pwd。那么,两者的用法有何不同?或应为特定目的选择什么?

Answers:


10

那要看你在做什么。首先,$PWD是环境变量,pwd是内置的shell或实际的二进制文件:

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

现在,$PWD除非您使用-P标志,否则内置的bash会简单地打印的当前值。如中所述help pwd

pwd: pwd [-LP]
Print the name of the current working directory.

Options:
  -L    print the value of $PWD if it names the current working
    directory
  -P    print the physical directory, without any symbolic links

By default, `pwd' behaves as if `-L' were specified.

pwd二进制,而另一方面,通过获取当前目录下getcwd(3)的系统调用,它返回相同的值readlink -f /proc/self/cwd。为了说明,请尝试进入一个目录,该目录是另一个目录的链接:

$ ls -l
total 4
drwxr-xr-x 2 terdon terdon 4096 Jun  4 11:22 foo
lrwxrwxrwx 1 terdon terdon    4 Jun  4 11:22 linktofoo -> foo/
$ cd linktofoo
$ echo $PWD
/home/terdon/foo/linktofoo
$ pwd
/home/terdon/foo/linktofoo
$ /bin/pwd
/home/terdon/foo/foo

因此,总之,在GNU系统(例如Ubuntu)上,pwdecho $PWD等效,除非您使用该-P选项,但与之/bin/pwd不同且行为类似于pwd -P


一个区别是,在可用时使用$ PWD可以避免派生子命令,例如echo或pwd。这对于性能和程序跟踪来说是有利的。
Joe Atzberger 2014年

3

如果对所有工作目录(包括在符号链接中时)都使用不带选项的选项,则两者将返回相同的结果。

但是,来自man pwd

-P, --physical
    avoid all symlinks

这意味着pwd -P在指向其他目录的符号链接中执行时,将打印原始目录的路径。

例如,如果您有一个指向的符号链接/var/run/run并且您当前在/var/run/目录中,则执行

echo $PWD

将返回:

/var/run

并且将与相同pwd。但是,如果执行:

pwd -P

将返回

/run

因此,这取决于您所需的路径:没有符号链接的实际路径或忽略符号链接的当前目录。pwd -P和之间的唯一区别echo $PWD是存在符号链接。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.