pwd 和 $PWD 使用上的区别

Pan*_*dya 12 command-line

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

ter*_*don 13

这取决于你在做什么。首先,$PWD是一个环境变量,pwd是一个内置的 shell 或一个实际的二进制文件:

$ type -a pwd
pwd is a shell builtin
pwd is /bin/pwd
Run Code Online (Sandbox Code Playgroud)

现在,$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.
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

所以,综上所述,在GNU系统(如Ubuntu),pwd并且echo $PWD是等价的,除非你使用的-P选项,但/bin/pwd不同的是,并且表现得像pwd -P