Let's say we are in a blank directory. Then, the following commands:
mkdir dir1
cp -r dir1 dir2
Yield two (blank) directories, dir1
and dir2
, where dir2
has been created as a copy of dir1
. However, if we do this:
mkdir dir1
mkdir dir2
cp -r dir1 dir2
Then we instead find that dir1
has now been put inside dir2
. This means that the exact same cp
command behaves differently depending on whether the destination directory exists. If it does, then the cp
command is doing the same as this:
mkdir dir1
mkdir dir2
cp -r dir1 dir2/.
This seems extremely counter-intuitive to me. I would have expected that cp -r dir1 dir2
(when dir2
already exists) would remove the existing dir2
(and any contents) and replace it with dir1
, since this is the behavior when cp
is used for two files. I understand that recursive copies are themselves a bit different because of how directories exist in Linux (and more broadly in Unix-like systems), but I'm looking for some more explanation on why this behavior was chosen. Bonus points if you can point me to a way to ensure cp
behaves as I had expected (without having to, say, test for and remove the destination directory beforehand). I tried a few cp
options without any luck. And I suppose I'll accept rsync
solutions for the sake of others that happen upon this question who don't know that command.
In case this behavior is not universal, I'm on CentOS, using bash.
Best Answer
The behaviour you're looking for is a special case:
Therefore I'd say it's not possible to make
cp
do what you want.Since your expected behaviour is "
cp -r dir1 dir2
(whendir2
already exists) would remove the existingdir2
(and any contents) and replace it withdir1
":You don't even need to check if
dir2
exists.The
rsync
solution would be adding a trailing/
to the source so that it doesn't copydir1
itself intodir2
but copies the content ofdir1
todir2
(it will still keep existing files indir2
):