Shell – Comparing each file in two directories and copying it to another if it differs from its counterpart

file-copyshell

How can I compare all files in two directories and copy the ones that are different to another directory? For example, say we have dir1 and dir2:

dir1:
     build.gradle
     gradle.properties
     somejar.jar
     javacode.java
     anotherjar.jar

dir2:
     build.gradle      <-- different from build.gradle in dir1
     gradle.properties
     somejar.jar
     javacode.java     <-- different from javacode.java in dir1
     yetanotherjar.jar

How may I create a new directory dir3 that contains the different files from dir2, the common files in dir1 and dir2 and all uncommon files in both dir1 and dir2? dir3 should contain:

dir3:
     build.gradle      <-- from dir2
     gradle.properties <-- these are common files both in dir1 and dir2
     somejar.jar       <--
     javacode.java     <-- from dir2
     anotherjar.jar    <-- from dir1
     yetanotherjar.jar <-- from dir2

Best Answer

All you need is

cp -n dir2/* dir1/* dir3/
Related Question