当你涉及软链接时,“cd ..”和“pwd”真正意味着什么?

时间:2014-10-04 05:52:43

标签: linux unix filesystems symlink

请参阅下面的Unix命令。 当我们处理软链接时,每个目录的根目录可以有多条路径。 那么在这种情况下,如何计算pwdcd ..?这意味着目录路径不再是无状态的,对吧?

$ cd ~
$ mkdir a b
$ cd a
$ ln -s ~/b b
$ cd b
$ pwd
/home/myuser/a/b

$ cd ..
$ pwd
/home/myuser/a

2 个答案:

答案 0 :(得分:1)

看看这个例子:

[myuser@test ~]$ pwd
/home/myuser
[myuser@test ~]$ mkdir a b
[myuser@test ~]$ cd a
[myuser@test a]$ ln -s ~/b b
[myuser@test a]$ cd b
[myuser@test b]$ pwd
/home/myuser/a/b
[myuser@test b]$ pwd -P 
/home/myuser/b
[myuser@test b]$ echo $$ 
2432
[myuser@test b]$ ls -l /proc/2432/cwd
lrwxrwxrwx 1 myuser myuser 0 Oct  4 04:10 /proc/2432/cwd -> /home/myuser/b
[myuser@test b]$ 
[myuser@test b]$ 
[myuser@test b]$ pwd
/home/myuser/a/b
[myuser@test b]$ cd -P .. 
[myuser@test ~]$ pwd
/home/myuser
[myuser@test ~]$ 
[myuser@test ~]$ env | grep "PWD"
PWD=/home/myuser
OLDPWD=/home/myuser/a/b

从bash手册中查看选项-P to cd:

-P      If set, the shell does not follow symbolic links when executing commands such  as  cd  that
                  change  the  current  working directory.  It uses the physical directory structure instead.
                  By default, bash follows the logical chain of directories when  performing  commands  which
                  change the current directory.

正如你所看到的,当前目录由内核保存的是你的真实目录(/ proc / 2432 / cwd - > / home / myuser / b)但bash可以做任何想要跟随符号链接的事情, 因为cd是bash内部命令。

答案 1 :(得分:0)

命令总是根据软链接后面的实际(已解析)目录计算。 当你这样做

$ cd b   ; you end up in the directory pointed by b

根据此新位置解决此处的任何命令