Copy and overwrite directory recursively

Have you tried rsync ?

From your requirements I think it is the best tool. It will replace only the files that changed, copy new ones and it can remove those that are gone in origin.

$ rsync -av --delete temp/ existing_folder/

Notice the slash after temp, it is required because you want to sync the contents. Without it it would create a directori temp inside existing folder.

The delete argument makes the files that are no longer in temp be removed in existing_folder.

You can also do a dry-run if you add -n argument. It will tell you what changes will be done without doing anything.


If both orig_folder and temp are on the same physical hard drive, renaming (moving) them is essentially instantaneous. That means you could simply do

mv orig_folder foo && mv temp orig_folder && rm -rf foo

That will rename orig_folder to foo, then rename temp to orig_folder and finally delete foo. On the same filesystem, the two mv operations will take next to no time (0.004 seconds on my system).

If the source and target directories are not on the same file system, in order to minimize the time that the files are not available, you would first need to move the source directory to the same filesystem and then rename:

mv /path/to/temp . && mv orig_folder foo && mv temp orig_folder && rm -rf foo

Combining the accepted answer here with the command to copy one directory into another, the below command should do the job:

rm -rfv <existing_folder>/* && cp -r <temp>/* <existing_folder>

But, as the answer in the link says, note that:

  • the /* part is very important. If you put a space before the *, it will delete all your files in your current directory.
  • this won't delete hidden files
  • "be very (very) careful playing with rm, -r and * all in the same command. They can be a disastrous combination."