Watch for undocumented behavior of cp -R

Nov 16, '05 06:49:00AM

Contributed by: ojohns

The man page for cp says that cp -R directory1 directory2 "...copies the directory and the entire subtree connected at that point." But it doesn't always do that! For example, do the following:

$ cd /tmp
$ mkdir Afolder
$ cd Afolder
$ touch file1
$ touch file2
$ touch file3
$ cd ..
$ cp -R Afolder ~/
If you now cd to your home folder, you will find Afolder there, with files 1, 2, and 3 inside it. This is the documented behavior. But, now do the same experiment again, but this time use this copy command:
$ cp -R Afolder/ ~/
If you look in your home directory now, you will find files 1, 2, and 3 there, but no Afolder. Darwin takes the trailing / on Afolder as a flag to tell it to copy the contents only, and not the enclosing directory Afolder. This is either a bug, or a very annoying feature. You might ask who would put a trailing / on a folder anyhow? Well, if you use Tab completion, as in Afol [Tab] to complete the name automatically, the terminal will automatically add the trailing /.

The workaround is to watch carefully for the trailing /. But it is easy to get caught, which can be a disaster when you are copying a folder containing lots of files with names similar to ones in the target directory.

Comments (38)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20051112100007372