Shell – cp SOMEFILE .. copies to a different directory after cd’ing via a symbolic link

cd-commandcpshellsymlink

Consider the following setup:

~/Desktop/Public/subdir
~/Desktop/subdir --> ~/Desktop/Public/subdir (symbolic link)

Now I do:

cd ~/Desktop/subdir

Which leads me into the linked directory.

If I now issue the command:

cd ..

I will be moved back into the Desktop directory. This means the cd command is context sensitive – it remembers that I entered subdir via the symbolic link.

However, issuing the command

cp testfile ..

will copy testfile into Desktop/Public.

I prefer the behavior of cd over the (often unpredictable) behavior of cp. In any case, I wonder what is the reason for this difference in behavior? Just a legacy thing or is there a good reason?

Best Answer

The reason that cd is aware that you have entered the directory via a symlink is because it is built-in to the shell. The cp command is an external binary and is only passed data via command line arguments and environment variables. Environment variables do not contain data on how you entered the current directory.

If you are using bash, you can make cd function the same as cp if you want things to be consistent. set -P will accomplish this. From the manpage:

          -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.
Related Question