How can I copy a directory structure, dir1, to dir2, (with all the subdirectories) on Unix using the terminal window?
3 Answers
cp -rf /source/path/ /destination/path/
-r
= recursive, copies all the sub-directories
-f
= force, if an existing destination file cannot be opened, remove it and try again
Note You should be careful when using the -f
flag because it will forcefully overwrite anything you copy to. Thank @Nifle for this suggestion.
You may want to use the * wildcard to copy all of the files in the directory if you need to.
-
11I don't agree that you should use the
f
flag.-f if an existing destination file cannot be opened, remove it and try again
– NifleDec 15, 2010 at 15:52 -
Personally I always use the -f flag. Isn't a good practice so perhaps you are right.– qrobertsDec 15, 2010 at 15:53
-
If you know what it does, and you know what you are doing it's OK. But in this case with an inexperienced user it might not be suitable.– NifleDec 15, 2010 at 15:57
-
@Nifle Yeah, I understand what you are saying. Just that if he forces it, the chances of it working are better than if he didn't. It all depends upon what you are doing and that you understand what it does.– qrobertsDec 15, 2010 at 15:59
-
If you put a note in your answer about the
-f
flag being useful if you are copying <source> over <dest> (as in overwriting things in <dest>) I'll upvote it myself and delete my answer)– NifleDec 15, 2010 at 16:02
While the cp -R
answers are right (BTW the case of the flag on BSD must be capital, both are supported on linux), there is an old incantation involving tar:
$ tar cf - . | (cd DIR; tar xf - )
Why the heck would you do that? Because tar has a fairly sophisticated understanding of links both hard and symbolic.
Do you want you copy to replace existing symbolic links with one that have the same text? Or with links to the same target (adjusting relative paths to compensate)? Or with bitwise copies of the target?
If two files in the original are hard linked should the new structure have two copies of the data or just one?
Decisions, decisions. Tar has sensible defaults, but lets you be very specific about it.
I like
cp -axv source dest
Rsync is another good tool for this
rsync -va source dest