符号链接上的 cd/bash 行为



>假设我的主文件夹中有文件夹 ~/a/b,并且文件夹 b 包含指向名为"符号链接"的".."的符号链接。然后我在砰:

hm@mach:~$ cd a/b/symlink
hm@mach:~/a/b/symlink$ pwd -P
/home/hm/a
hm@mach:~/a/b/symlink$ cd ..
hm@mach:~/a/b$ pwd -P
/home/hm/a/b

pwd -P 打印当前工作目录,取消引用所有符号链接。为什么工作目录/home/hm/a/b 在末尾,而不是/home/hm?

根据help cd

  Options:
      -L        force symbolic links to be followed: resolve symbolic
                links in DIR after processing instances of `..'
      -P        use the physical directory structure without following
                symbolic links: resolve symbolic links in DIR before
                processing instances of `..'

换句话说,-L意味着使用逻辑结构,而-P使用实际的物理目录结构。

逻辑结构是这样的,

$ tree a
a
└── b
    └── symlink -> ..

当你去a/b/symlink时,实际的物理结构是,

a

如果要使用..,那么还必须使用cd -P

          The -P option says to use the physical directory
          structure instead of following symbolic links (see
          also the -P option to the set builtin command);
          the -L option forces symbolic links to be followed.

举个例子,

$ cd
$ cd a/b/symlink   # physical location is at a/
$ cd ..            # now is at a/b
$ cd symlink       # goes back to a/b/symlink
$ cd -P ..         # follow physical path (resolve all symlinks)
$ pwd -P           # -P is optional here to show effect of cd ..
/home/sarnold
$ 

bash跟踪逻辑当前目录路径,如提示符所示,并根据该路径解释cd ..之类的内容。 如果您仅在cd(或pushd)中使用此类路径,这将使事情更加一致,但代价是意外事件发生,如果您随后期望命令参数(或命令内部; emacsvim都有自己的可配置的符号链接处理规则,但大多数命令依赖于内核来处理它)。

最新更新