How to copy-merge two directories?
This is a job for rsync. There's no benefit to doing this manually with a shell loop unless you want to move the file rather than copy them.
rsync -a /path/to/source/ /path/to/destination
In your case:
rsync -a /images2/ /images/
(Note trailing slash on images2
, otherwise it would copy to /images/images2
.)
If images with the same name exist in both directories, the command above will overwrite /images/SOMEPATH/SOMEFILE
with /images2/SOMEPATH/SOMEFILE
. If you want to replace only older files, add the option -u
. If you want to always keep the version in /images
, add the option --ignore-existing
.
If you want to move the files from /images2
, with rsync, you can pass the option --remove-source-files
. Then rsync copies all the files in turn, and removes each file when it's done. This is a lot slower than moving if the source and destination directories are on the same filesystem.
The best choice, as already posted, is of course rsync
. Nevertheless also unison
would be a great piece of software to do this job, though typically requires a package install. Both can be used in several operating systems.
Rsync
rsync synchronizes in one direction from source to destination. Therefore the following statement
rsync -avh --progress Source Destination
syncs everything from Source to Destination. The merged folder resides in Destination.
-a means "archive" and copies everything recursively from source to destination preserving nearly everything.
-v gives more output ("verbose").
-h for human readable.
--progress to show how much work is done.
If you want only update the destination folder with newer files from source folder:
rsync -avhu --progress source destination
Unison
unison synchronizes in both directions. Therefore the following statement
unison Source Destination
syncs both directories in both directions and finally source equals destination. It's like doing rsync twice from source to dest and vice versa.
For more advanced usages look at the man pages or the following websites:
- https://www.cis.upenn.edu/~bcpierce/unison/
- https://rsync.samba.org/
for dir in images2/*; do mv "$dir"/* "images/$(basename "$dir")"; done
Loop over all the contents of images2
using an expanded glob (to avoid the problems with parsing ls
) then mv
the contents of those items to the matching entry in images
. Uses basename
to strip the leading images2
from the globbed path.