Skip to content
Sand Software Solutions

Compare two folders by checksum: which files changed?

Published · 1 min read

You want to know whether a backup is right, or what changed inside a folder. First mind the difference between comparing by date and size and comparing by content. A file can get a new date without any change to it, and the other way round.

The examples use two folders, original and copy.

Windows: PowerShell compares content

This function takes a SHA-256 hash of every file. Compare-Object then shows only the differences.

function Get-Hashes($root) {
  $full = (Resolve-Path $root).Path
  Get-ChildItem $full -Recurse -File | ForEach-Object {
    [pscustomobject]@{
      Path = $_.FullName.Substring($full.Length + 1)
      Hash = (Get-FileHash $_.FullName -Algorithm SHA256).Hash
    }
  }
}

Compare-Object (Get-Hashes .\original) (Get-Hashes .\copy) -Property Path, Hash | Sort-Object Path

<= means this version exists only in original, => only in copy. A path listed twice has different content. No output means the folders match.

Windows: robocopy looks at date and size

robocopy .\original .\copy /L /E /NJH /NJS

Because of /L nothing is copied, you only get a listing. It is fast, but robocopy does not read the content: in our test a file with exactly the same content showed up as Older, only because its date differed.

Linux and macOS: diff

diff -rq original copy

This compares content and also names files that exist on one side only. The exit status is 1 when there are differences.

Linux: an rsync dry run

rsync -rnc --delete --itemize-changes original/ copy/

-n changes nothing, -c compares checksums. The lines describe what rsync would do to make copy match: *deleting is an extra file in copy, >f+++++++++ is a file missing there. Mind the trailing slashes and keep the -n.

What if the original is gone?

Every method above needs both folders at the same time. To check later whether something changed, record the hashes now. sha256sum can do that, but sha256sum -c does not report files that were added afterwards.

That is why we made Assay, a small open source program:

$ assay seal ./original -m original.assay.json
Sealed 4 files -> original.assay.json

$ assay check ./copy -m original.assay.json
  modified  a.txt (7 B -> 8 B)
  added     new.txt
  removed   c.txt
CHANGED: 1 modified, 1 added, 1 removed, 0 renamed, 2 unchanged

The manifest is a separate file you can keep somewhere else. Bear in mind that whoever can change both the files and the manifest can hide a change. Store the manifest apart, or sign it.

More about Assay

← All posts

A question or an idea?

Send us an email. You talk directly to the people who build the software and get an answer within 2 working days.