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.