20

Say I have two folders with various content, foo and bar. How can I merge bar into foo so that:

  • Files in foo that are not in bar are untouched.
  • Files in bar that are not in foo are now in foo.
  • Files in foo that are also in bar have been replaced by the files from bar.
28

If I'm reading your requirements correctly, there's no files that go from foo to bar. It looks like you can just copy the contents of bar to foo, letting it overwrite files as necessary (its default behavior).

$ cp -R /path/to/bar/* /path/to/foo
3
  • Yeah, what I was uncertain about was the recursiveness and how to not end up with just having bar inside foo as foo/bar. But this seems to be what I want :) – Svish Feb 7 '11 at 12:57
  • 1
    Right, if you just did cp -R /path/to/bar /path/to/foo it would create a directory bar inside foo. Subtle point. – coneslayer Feb 7 '11 at 13:20
  • 1
    Note: it will omit hidden files/directories in bar (i.e. with names starting with a dot – .) because of how shell globbing works. – Kamil Maciorowski Jun 15 '17 at 17:10
10

I had a very similar need: merge bar into foo but files which are in bar should not overwrite matching files in foo. In this case:

$ cp -R -n /path/to/bar/* /path/to/foo/
4

Try this :

$ cp -r-u-v /path/to/foo/* /path/to/bar/

From man cp
-u, --update copy only when the SOURCE file is newer than the destination file or when the destination file is missing
-R, -r, --recursive copy directories recursively

3
  • 2
    Two people have already suggested the cp command and so your answer seems superfluous. Taking a few minutes to explain how the arguments you've selected do a better job than the other suggestions will help make your answer more helpful. – music2myear Jun 15 '17 at 17:21
  • 1
    The -u flag updates only if the file in the source is newer that the one in the destination. See : man cp -> -u, --update : copy only when the SOURCE file is newer than the destination file or when the destination file is missing – drew7721 Jun 16 '17 at 17:52
  • Add that information to the question (use Edit right below your post) so that people can see that helpful information in the answer itself. – music2myear Jun 16 '17 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.