6

I want to copy a directory from:

path1/dir1

to

path2/dir2

the first time I invoke

cp -r path1/dir1 path2/dir2

there's no problem, dir2 is created under path2

ls path2/dir2

bu the 2nd time, dir1 is created under path2/dir2

ls path2/dir2/dir1

Can I get the correct behavior using only cp ? (= without invoking rm -f path2/dir2 )

Pierre
  • 1,793

2 Answers2

8

Use the -T option to cp (GNU cp):

cp -rT path2/dir2 path1/dir1

If you use rsync for this (which is probably what you want since it will avoid copying files which haven't changed), you can append a / to the source directory so that specifically the contents are copied rather than the directory itself. Eg:

rsync -r path1/dir1/ path2/dir2
Graeme
  • 34,027
2

It's ambiguous what you want the behaviour to be when "copying" a directory to a destination that already exists. Do you want to

  • add new files only?
  • add new files and update files whose contents have changed?
  • add and update files, and delete files at the destination that have since been removed from the source?

Basically, what you think of as a simple copy operation is actually much more complicated — too complicated for cp. In all cases, you want to use the rsync command instead.

200_success
  • 5,535