How can I copy a directory structure, dir1, to dir2, (with all the subdirectories) on Unix using the terminal window?

  • 2
    " cp -r /dir1 /dir2 " Is this right ?? Dec 15, 2010 at 15:55
  • Yes, that is correct. You may want to mark one of the answers as your solution.
    – qroberts
    Dec 15, 2010 at 15:56

3 Answers 3

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.

  • 11
    I don't agree that you should use the f flag. -f if an existing destination file cannot be opened, remove it and try again
    – Nifle
    Dec 15, 2010 at 15:52
  • Personally I always use the -f flag. Isn't a good practice so perhaps you are right.
    – qroberts
    Dec 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.
    – Nifle
    Dec 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.
    – qroberts
    Dec 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)
    – Nifle
    Dec 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .