Compare any two files with git diff --no-index

git diff --no-index before.txt after.txt

git diff --no-index before.txt after.txt compares two files on disk with Git’s diff, whether or not they’re in a repository. You get Git’s colors, its pager and its options, --word-diff included, for any two files.

git diff --no-index before.txt after.txt
diff --git a/before.txt b/after.txt
index 4aee996..abdfb0c 100644
--- a/before.txt
+++ b/after.txt
@@ -1,5 +1,6 @@
 name: api
-image: api:1.4
+image: api:1.5
 replicas: 2
 port: 8080
-log: info
+log: debug
+timeout: 30

That’s Git 2.39. The hunk is the one diff -u prints and the tool below shows under Unified diff; both Git and the tool use Myers’ algorithm. The headers differ: a/ and b/ prefix the names, and the index line holds the start of each file’s blob hash, what git hash-object before.txt prints in full (4aee9965b0bc…), followed by the file mode.

Inside a repository

Within a Git working tree, git diff before.txt after.txt without --no-index reads both names as paths to filter by: it shows uncommitted changes to those two files, so for two committed, unchanged files it prints nothing and exits 0. Add --no-index. Outside a working tree, or when one of the paths is outside it, Git compares the files without being told.

Exit codes

--no-index implies --exit-code, as diff does it: 0 when the files match, 1 when they differ. git diff --no-index --quiet a b prints nothing and only sets the status, which suits an if. Plain git diff in a repository exits 0 even with changes unless you pass --exit-code.

Changed words instead of lines

git diff --no-index --word-diff before.txt after.txt
name: api
image: [-api:1.4-]{+api:1.5+}
replicas: 2
port: 8080
log: [-info-]{+debug+}
{+timeout: 30+}

A word here is a run of non-space characters, the same unit as the tool’s table, which marks api:1.4/api:1.5 and info/debug inside the paired lines. --word-diff=color (or --color-words) colors the words instead of bracketing them, and --word-diff-regex=. compares characters: image: api:1.[-4-]{+5+}.

Other options that carry over

  • -w and -b ignore white space as diff does; --ignore-cr-at-eol ignores only CRLF against LF.
  • --stat summarizes: before.txt => after.txt | 5 +++--.
  • --diff-algorithm=histogram or patience can read better when blocks of code move.
  • Directories work too: git diff --no-index old/ new/ compares the files in each.

Try it in the Diff Checker

3 lines added · 2 lines removed

BeforeAfter
1name: api1name: api
2image: api:1.42image: api:1.5
3replicas: 23replicas: 2
4port: 80804port: 8080
5log: info5log: debug
6timeout: 30
Unified diff
--- before
+++ after
@@ -1,5 +1,6 @@
 name: api
-image: api:1.4
+image: api:1.5
 replicas: 2
 port: 8080
-log: info
+log: debug
+timeout: 30

Runs in your browser. Nothing you enter is sent anywhere.