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:


     build.gradle      <-- different from build.gradle in dir1
     javacode.java     <-- different from javacode.java in dir1

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:

     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

All you need is

cp -n dir2/* dir1/* dir3/

Do I understand you correctly in that dir3 should contain all files from the two base directories, and if a file appears in both directories, the one from dir2 should be taken? Then a simple

cp dir1/* dir3/
cp dir2/* dir3/

should do the trick: Files that differ in both source directories will be overwritten with the version from dir2. If you do not want to copy identical files twice, you might also rsync them instead of cping.


One way to do it:

cp -a /path/to/dir2/* /path/to/dir3
cd /path/to/dir1
comm -23 <(ls -1 | sort) <(cd /path/to/dir2; ls -1 | sort) | cpio -pam /path/to/dir3

This assumes you only have files (i.e. no subdirectories) in dir1 and dir2, and your filenames don't contain newlines. It also assumes your shell is smart enough to handle <(...) constructs.


cp -pu dir2/* dir1/* dir3/

from man:

-p    same as --preserve=mode,ownership,timestamps
-u    copy only when the SOURCE file is  newer  than  the  destination
      file or when the destination file is missing


  1. Always put the updated directory first. (From example above: cp -pu dir1/* dir2/* dir3/ will not copy the updated files)
  2. dir3 must exist.
  • 3
    cp -u only works if every duplicate file in dir2 is an edit from the one in dir1. If both could have changed independently, it is not clear which one is newer. – klimpergeist Jul 18 '15 at 14:43

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.