简体   繁体   English

cd/bash 在符号链接上的行为

[英]Behavior of cd/bash on symbolic links

Assume I have the folders ~/a/b in my home folder, and the folder b contains a symbolic link to '..' named 'symlink'.假设我的主文件夹中有文件夹 ~/a/b,并且文件夹 b 包含一个名为“symlink”的“..”符号链接。 Then I perform the following actions in bash:然后我在 bash 中执行以下操作:

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 prints the current working directory, dereferencing all symbolic links. pwd -P 打印当前工作目录,取消引用所有符号链接。 Why is the working directory /home/hm/a/b at the end, and not /home/hm?为什么最后是工作目录/home/hm/a/b,而不是/home/hm?

According to help cd ,根据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 `..'

In other words, -L means using the logical structure, whereas -P uses the actually physical directory structure.换句话说, -L表示使用逻辑结构,而-P使用实际物理目录结构。

The logical structure is like this,逻辑结构是这样的

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

The actual physical structure when you go to a/b/symlink is,当你去a/b/symlink时的实际物理结构是,

a

If you want to use the real .. , then you must also use cd -P :如果你想使用真正的.. ,那么你还必须使用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.

An example,一个例子,

$ 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 keeps track of the logical current directory path, as shown in your prompt, and interprets things like cd .. according to that. bash跟踪当前的逻辑目录路径,如您的提示所示,并据此解释cd .. This makes things a little more consistent if you only use such paths in cd (or pushd ), at the cost of unexpected things happening if you then expect the same thing to happen with paths in command arguments (or inside commands; emacs and vim have their own configurable rules for symlink handling, but most commands rely on the kernel to deal with it).如果您只在cd (或pushd )中使用这样的路径,这会使事情更加一致,代价是发生意外的事情,如果您希望命令参数中的路径(或内部命令; emacsvim有)发生同样的事情他们自己的符号链接处理可配置规则,但大多数命令依赖内核来处理它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM