Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 )

share|improve this question
    
are you trying to replace dir2 with dir1 in path2/? –  user61786 Apr 14 at 10:12

2 Answers 2

up vote 6 down vote accepted

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
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.