cp SOMEFILE .. cd'ing 后通过符号链接复制到不同的目录

Kon*_*ert 5 shell cp cd-command symlink

考虑以下设置:

~/Desktop/Public/subdir
~/Desktop/subdir --> ~/Desktop/Public/subdir (symbolic link)
Run Code Online (Sandbox Code Playgroud)

现在我这样做:

cd ~/Desktop/subdir
Run Code Online (Sandbox Code Playgroud)

这使我进入链接目录。

如果我现在发出命令:

cd ..
Run Code Online (Sandbox Code Playgroud)

我将被移回Desktop目录。这意味着 cd 命令是上下文敏感的——它记得我是subdir通过符号链接输入的。

但是,发出命令

cp testfile ..
Run Code Online (Sandbox Code Playgroud)

将复制testfileDesktop/Public.

我喜欢的行为cd上的(通常不可预测的)行为cp。无论如何,我想知道这种行为差异的原因是什么?只是遗留问题还是有充分的理由?

jor*_*anm 3

之所以cd知道您已通过 a 进入目录,symlink是因为它是内置于 shell 中的。该cp命令是外部二进制文件,仅通过命令行参数和环境变量传递数据。环境变量不包含有关您如何进入当前目录的数据。

如果您使用bash,您可以使cd功能相同,就像cp您希望事情保持一致一样。set -P将实现这一点。从联机帮助页:

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

  • 实际上,PWD 环境变量确实包含有关您如何进入当前目录的数据。`cp` 只是不像 Bash 那样使用它。 (4认同)