Subject: bug#32455: cp gets confused by symlinks to parent directory

From: Mike Crowe <[email-masked]>
Date: Thu, 16 Aug 2018 15:47:12 +0100

If cp is passed the -d option and told to copy a symlink to the directory
containing the symlink then it ends up removing the target directory so it
is unable to create the symlink.

Reproduction script:

--8<--
#!/bin/sh
set -x

rm -rf temp
mkdir -p temp/src temp/dest

ln -s . temp/src/self

# This one works
cp -vd temp/src/self temp/dest/self
# This one fails
cp -vd temp/src/self temp/dest/self
# This one works again
cp -vd temp/src/self temp/dest/self
-->8--

Output:

--8<--
+ rm -rf temp
+ mkdir -p temp/src temp/dest
+ ln -s . temp/src/self
+ cp -vd temp/src/self temp/dest/self
'temp/src/self' -> 'temp/dest/self'
+ cp -vd temp/src/self temp/dest/self
removed 'temp/dest/self/self'
'temp/src/self' -> 'temp/dest/self/self'
cp: cannot create symbolic link 'temp/dest/self/self': No such file or directory
+ cp -vd temp/src/self temp/dest/self
'temp/src/self' -> 'temp/dest/self'
-->8--

(coreutils 8.26, 8.28 and 8.30 all appear to behave the same way.)

Expected behaviour:

There should be no error message emitted by the second invocation of cp,
and the target directory should be in the same state as it is after the
first or third attempts to copy the symlink.

Or, maybe I'm fundamentally misunderstanding something. I couldn't find
this mentioned in the FAQ or "gotchas".

Thanks.

Mike.