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.
cp file1 file2
to append iffile2
exists, I expect it to overwrite. My basis for anticipated behavior is on a literal interpretation of the syntax and on what is done with files, though other users may expect differently. – TTT Dec 08 '14 at 19:29> file
truncates a file, shouldn't>directory
be equivalent torm -r directory; mkdir directory
? – muru Dec 08 '14 at 20:04>
redirection is placing contents and not files/directories themselves, I wouldn't expect that behavior to be possible (it isn't) since you'd be writing data directly to a directory, rather than a file in a directory. My idea ofcp -r
overwriting isn't that I think that behavior is better, but just that it's consistent. I'd be equally content ifcp file1 file2
andcp -r dir1 dir2
both appended. But, neither do. Instead, one (over)writes while the other's behavior depends on the situation. – TTT Dec 08 '14 at 20:28ls
by default,rm
,touch
when given a non-existent directory as argument, etc.) that that argument doesn't hold water. – muru Dec 08 '14 at 20:33