Macos – Diff between two directories and keep only the unchanged ones

bashdiff()macos

I need to diff two directories:

 A: /path1/
 B: /path2/
  1. The directory A contains all files and subdirectories that are also contained in B.
  2. The files in A (and in its subdirectories) can have different contents of the equivalent files in B.
  3. The directory A (and its subdirectories) also has extra files that do not exist in B.

What I would like to achieve is:

  • Keep only the files in A that differ from the files in B plus all the extra files that don't exist in B.
  • Delete all the other files in A that do not respect the previous rule.

Best Answer

This approach should work:

cd /path1

find . -type f -exec cmp -s {} /path2/{} \; -delete

How it works:

  • find . -type f goes through all files in the current directory (A) and its subdirectories.

  • cmp -s {} /path2/{} silently (-s) compares the currently processed file ({}) to the matching file in B (/path2/{}).

  • If the files are identical, cmp returns true and the -exec condition matches.

  • If the -exec condition matches, -delete deletes the file.

I suggest replacing -delete with -print before running the actual command to verify if it works as expected.


To deal with leftover empty directories, you can execute the command:

find . -type d -exec rmdir -p {} \; 2> /dev/null
  • -type d only finds directories.

  • -exec rmdir -p {} \; executes rmdir -p {} for every directory that has been found.

    {} is the directory that has been found, and the -p switch makes rmdir remove its empty parent directories as well.

  • 2> /dev/null suppresses the error messages that will arise from trying to delete non-empty or previously deleted directories.

Since rmdir cannot delete non-empty directories, this should be the safest way.

Related Question