Copying a directory+renaming it

cp

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 )

Best Answer

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