cp -r src/* dest/

If src/ & dest/ both contain a directory foo, the contents of src/foo/ are copied into dest/foo/, which is desired.

If dest/ instead contains a symlink foo -> /sym/foo to a directory elsewhere, the command errors:

cp: cannot overwrite non-directory 'dest/foo' with directory 'src/foo'

Is it possible to copy following the target symlink, with GNU cp? As far as I can tell it only has an option (-L/--dereference) for following source symlinks.

  • I assume that the target of foo really is a directory? Dec 6, 2019 at 23:02
  • Yes, I've edited the question to be clearer about that.
    – OJFord
    Dec 8, 2019 at 13:34

1 Answer 1


You can achieve this behaviour with rsync's --keep-dirlinks option:

From man rsync (1):

-K, --keep-dirlinks

This option causes the receiving side to treat a symlink to a directory as though it were a real directory, but only if it matches a real directory from the sender. Without this option, the receiver’s symlink would be deleted and replaced with a real directory.

For example, suppose you transfer a directory "foo" that contains a file "file", but "foo" is a symlink to directory "bar" on the receiver. Without --keep-dirlinks, the receiver deletes symlink "foo", recreates it as a directory, and receives the file into the new directory. With --keep-dirlinks, the receiver keeps the symlink and "file" ends up in "bar".


rsync -av --keep-dirlinks src/ dest
  • Thanks, I anticipated rsync would probably do it; I was hoping to solve it neatly (more so than present for loop) without installing it. (So I won't accept this answer because I did say "with GNU cp", but thanks, and I'm sure it will be helpful to others.)
    – OJFord
    Dec 8, 2019 at 13:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .