To compare code in two files, run git diff --no-index old.py new.py. It works on any two files, inside a Git repository or not, and prints a unified diff showing which lines were removed (-) and added (+). Plain diff -u old.py new.py gives the same format on any Unix system. For anything harder than a small edit, the useful skills are reading hunk headers, ignoring noise (whitespace, line endings, key order) and picking the right algorithm or a syntax-aware tool like difftastic.
All output in this guide comes from commands run on macOS with Git 2.54.0, the system diff (Apple's, based on FreeBSD diff), jq 1.7.1, difftastic 0.72.0 and delta 0.20.1. The flags shown also exist in GNU diffutils and current Git. For a quick check without a terminal, paste both versions into the code difference checker.
Which Comparison Do You Need?
| Situation | Command | Why |
|---|---|---|
| Two files, any location | git diff --no-index a b |
Color, word diff and algorithms, no repo needed |
| No Git installed | diff -u a b |
Available on every Unix |
| One-word changes in long lines | git diff --no-index --word-diff a b |
Highlights words, not whole lines |
| Re-indented or reformatted code | git diff --no-index -w a b or difft a b |
Hides whitespace-only changes |
| Windows vs Unix line endings | diff -u --strip-trailing-cr a b |
CRLF stops showing every line as changed |
| Functions moved or reordered | --diff-algorithm=histogram --color-moved |
Cleaner alignment, moved blocks marked |
| Whole directories or releases | diff -rq A B / git diff --no-index --stat A B |
Shows which files differ first |
| JSON configs or API responses | diff <(jq -S . a.json) <(jq -S . b.json) |
Key order stops mattering |
| Visual review | code --diff a b |
Side-by-side in VS Code |
Reading a Unified Diff
Take two versions of a small Python module. The new one adds an import, passes an encoding, changes a default and reads the config path from an environment variable:
git diff --no-index old.py new.py
diff --git a/old.py b/new.py
index 0a84f63..fbc0e7a 100644
--- a/old.py
+++ b/new.py
@@ -1,15 +1,17 @@
import json
+import os
def load_config(path):
- with open(path) as f:
+ with open(path, encoding="utf-8") as f:
return json.load(f)
def get_timeout(config):
- return config.get("timeout", 30)
+ return int(config.get("timeout", 60))
def main():
- config = load_config("config.json")
+ path = os.environ.get("APP_CONFIG", "config.json")
+ config = load_config(path)
print(get_timeout(config))
Line by line:
--- a/old.pyand+++ b/new.pyname the "before" and "after" files.diff -uprints the same two lines, followed by each file's modification time.@@ -1,15 +1,17 @@is the hunk header.-1,15means this hunk covers 15 lines of the old file starting at line 1.+1,17means 17 lines of the new file starting at line 1. The new side is two lines longer because the change added three lines and removed one.- Prefixes. A space means context (unchanged),
-means only in the old file, and+means only in the new file. A modified line always appears as a removal followed by an addition.
Everything ended up in one hunk because the changes sit within six lines of each other. By default, Git and diff -u show 3 lines of context, and hunks whose context overlaps get merged. Cut the context with -U1 and you get four separate hunks:
@@ -1,2 +1,3 @@
import json
+import os
@@ -4,3 +5,3 @@ import json
def load_config(path):
- with open(path) as f:
+ with open(path, encoding="utf-8") as f:
return json.load(f)
@@ -9,3 +10,3 @@ def load_config(path):
def get_timeout(config):
- return config.get("timeout", 30)
+ return int(config.get("timeout", 60))
@@ -13,3 +14,4 @@ def get_timeout(config):
def main():
- config = load_config("config.json")
+ path = os.environ.get("APP_CONFIG", "config.json")
+ config = load_config(path)
print(get_timeout(config))
The text after the second @@ is Git's "function context". It is the nearest line above the hunk that looks like a definition. That's why the hunk inside get_timeout is labeled def load_config(path): the def get_timeout line is itself inside the hunk. Adding *.py diff=python to .gitattributes switches Git to its built-in Python pattern for in-repo diffs.
diff -u vs git diff --no-index
Both produce unified diffs and both exit with status 1 when the files differ and 0 when they match. That makes them usable in scripts and CI checks. The git diff documentation states that --no-index "implies --exit-code". You can even omit --no-index when you're outside a repository, or when one path is outside the working tree.
Prefer Git when it's installed. You get color, --word-diff, --color-moved, a choice of algorithms and external diff tools, none of which plain diff offers. Prefer diff in minimal containers and for its -q/-r directory reports. Its headers also carry timestamps, which patch ignores but humans sometimes want.
Word-Level Diffs for Long Lines
Line diffs are noisy when a 120-character line changes by one argument. --word-diff keeps the line diff but marks changes inside each line, with [-removed-] and {+added+} in plain mode:
git diff --no-index --word-diff old.py new.py
@@ -1,15 +1,17 @@
import json
{+import os+}
def load_config(path):
with [-open(path)-]{+open(path, encoding="utf-8")+} as f:
return json.load(f)
def get_timeout(config):
return [-config.get("timeout", 30)-]{+int(config.get("timeout", 60))+}
def main():
{+path = os.environ.get("APP_CONFIG", "config.json")+}
config = [-load_config("config.json")-]{+load_config(path)+}
print(get_timeout(config))
By default a "word" is any run of non-whitespace, so open(path) counts as a single word. For code, a regex that splits identifiers from punctuation is sharper:
git diff --no-index -U0 \
--word-diff-regex='[A-Za-z0-9_]+|[^[:space:]]' old.py new.py
@@ -1,0 +2 @@ import json
{+import os+}
@@ -5 +6 @@ def load_config(path):
with open(path{+, encoding="utf-8"+}) as f:
@@ -10 +11 @@ def get_timeout(config):
return {+int(+}config.get("timeout", [-30-]{+60)+})
@@ -14 +15,2 @@ def main():
[-config-]{+path+} = [-load_config-]{+os.environ.get+}("{+APP_CONFIG", "+}config.json")
{+config = load_config(path)+}
The first three hunks are now precise: 30 became 60, and the code gained , encoding="utf-8" and an int( wrapper. The last hunk shows the trade-off. When a line was rewritten rather than edited, word-level matching pairs up unrelated tokens and becomes harder to read than the plain line diff. Use --color-words for the same thing with colors instead of markers.
Ignoring Whitespace and Line Endings
Wrapping a line in an if re-indents it, and a normal diff reports the re-indented line as removed and re-added. -w (--ignore-all-space) compares lines with all whitespace ignored:
git diff --no-index -w w1.py w2.py
@@ -1,5 +1,6 @@
-def total(items):
+def total(items, tax=0):
s = 0
for i in items:
+ if i.active:
s += i.price
- return s
+ return s * (1 + tax)
Without -w, s += i.price shows up as one removal and one addition. A milder option, -b (--ignore-space-change), only ignores changes in the amount of whitespace. Be careful with -w on Python, YAML or Makefiles, where indentation is meaning, not formatting.
Line endings are the other classic false positive. A file saved on Windows makes every line look changed, and piping through cat -v shows the culprit:
@@ -1,2 +1,2 @@
-host=db1
-port=5432
+host=db1^M
+port=5432^M
Both tools can ignore the trailing carriage return. diff -u --strip-trailing-cr unix.conf win.conf and git diff --no-index --ignore-cr-at-eol unix.conf win.conf each printed nothing and exited 0. Inside a repository, fix the cause with .gitattributes (* text=auto) rather than ignoring the symptom forever.
Diff Algorithms: myers, minimal, patience, histogram
--diff-algorithm changes how Git aligns the two files, not what changed. Git's documentation defines the options:
| Algorithm | What it does |
|---|---|
myers |
"The basic greedy diff algorithm." Still Git's default |
minimal |
Spends extra time to guarantee the smallest possible diff |
patience |
Anchors on lines that occur exactly once in both files, then diffs between them |
histogram |
Extends patience to "support low-occurrence common elements". Fast, and usually the most readable |
The difference shows up when code moves. Here a new fib function is added above frobnitz, and fact is deleted. Myers matches the generic lines ({, }, return 1;) first and interleaves the two functions:
@@ -1,26 +1,25 @@
#include <stdio.h>
-// Frobs foo heartily
-int frobnitz(int foo)
+int fib(int n)
{
- int i;
- for(i = 0; i < 10; i++)
+ if(n > 2)
{
- printf("Your answer is: ");
- printf("%d\n", foo);
+ return fib(n-1) + fib(n-2);
}
+ return 1;
}
-int fact(int n)
+// Frobs foo heartily
+int frobnitz(int foo)
{
- if(n > 1)
+ int i;
+ for(i = 0; i < 10; i++)
{
- return fact(n-1) * n;
+ printf("%d\n", foo);
}
- return 1;
}
--diff-algorithm=histogram on the same files tells the true story: fib was added whole, one printf was deleted, and fact was removed whole:
@@ -1,26 +1,25 @@
#include <stdio.h>
+int fib(int n)
+{
+ if(n > 2)
+ {
+ return fib(n-1) + fib(n-2);
+ }
+ return 1;
+}
+
// Frobs foo heartily
int frobnitz(int foo)
{
int i;
for(i = 0; i < 10; i++)
{
- printf("Your answer is: ");
printf("%d\n", foo);
}
}
-int fact(int n)
-{
- if(n > 1)
- {
- return fact(n-1) * n;
- }
- return 1;
-}
-
Both versions have the same size: --numstat reports 10 insertions and 11 deletions for each. minimal produced output identical to myers here, and patience matched histogram. "Smallest diff" and "most readable diff" are not the same goal. To make histogram your default, run git config --global diff.algorithm histogram.
Spotting Moved Code with --color-moved
When a block is cut from one place and pasted elsewhere, --color-moved colors those lines differently from real additions and deletions. Its default mode, zebra, detects moved blocks of at least 20 alphanumeric characters. --color-moved-ws=allow-indentation-change still counts a block as moved when its indentation changed. On the myers diff above, --color-moved highlighted // Frobs foo heartily and int frobnitz(int foo) as moved rather than deleted. It's a quick reviewer's signal that nothing was edited in transit. To enable it permanently:
git config --global diff.colorMoved zebra
Structural Diffs with difftastic
Difftastic (difft) parses both files with tree-sitter and compares syntax trees instead of lines. On the whitespace example above, difftastic 0.72.0 flagged exactly three changes:
- the new
if i.active:line; - the
, tax=0parameter; - the
* (1 + tax)expression.
The re-indented s += i.price was not marked as changed, with no flags needed. On the C example, it also narrowed the last change to the single token fact becoming fib.
Run it directly, or wire it into Git as the difftastic manual documents:
difft old.py new.py
# one-off, inside a repository
git -c diff.external=difft diff
git -c diff.external=difft log -p --ext-diff
To make it a git difftool instead, so plain git diff keeps producing patches, add this to ~/.gitconfig:
[diff]
tool = difftastic
[difftool]
prompt = false
[difftool "difftastic"]
cmd = difft "$MERGED" "$LOCAL" "abcdef1" "100644" "$REMOTE" "abcdef2" "100644"
[pager]
difftool = true
Then run git difftool. The odd-looking placeholder arguments are from the manual: they mimic the seven-argument external-diff calling convention so difftastic can show the real file name. Setting GIT_EXTERNAL_DIFF=difft for a single command does the same as diff.external. I tested all three routes with Git 2.54.
Know the limits. Difftastic's output is for humans: you can't feed it to git apply. By default it falls back to a line diff above 1 MB (--byte-limit). And it is structural, not semantic. When I reordered the keys of a JSON object, difftastic still reported every moved key as changed, because order is part of the syntax tree. Use --exit-code in scripts, because it exits 0 even when files differ unless you ask.
delta: A Better Pager for Git Diffs
delta doesn't change what Git compares. It re-renders Git's output with syntax highlighting, line numbers and within-line highlights, and the patch stays a normal patch. The recommended setup:
[core]
pager = delta
[interactive]
diffFilter = delta --color-only
[delta]
navigate = true
[merge]
conflictStyle = zdiff3
navigate = true lets you jump between files with n and N. A good split of roles: delta for everyday git diff and git log -p, difftastic on demand for reformatting-heavy changes. Both rely on 24-bit color and a decent monospace font, so your terminal matters. Warp vs Ghostty compares two popular choices.
Comparing in VS Code
code --diff old.py new.py
-d/--diff opens VS Code's side-by-side diff editor, which is good for long reviews and for copying hunks across. VS Code forks such as Cursor are built on the same editor core. The Cursor vs VS Code comparison covers what else differs. Add --wait when another program needs to block until you close the tab.
Comparing Two Directories
Start with a summary, then drill in:
diff -rq release-1.4 release-1.5
Only in release-1.5: LICENSE
Files release-1.4/requirements.txt and release-1.5/requirements.txt differ
Files release-1.4/src/app.py and release-1.5/src/app.py differ
Only in release-1.4/src: compat.py
git diff --no-index also accepts two directories, and --stat gives a diffstat:
/dev/null => release-1.5/LICENSE | 1 +
{release-1.4 => release-1.5}/requirements.txt | 2 +-
{release-1.4 => release-1.5}/src/app.py | 8 +++++---
release-1.4/src/compat.py => /dev/null | 1 -
4 files changed, 7 insertions(+), 5 deletions(-)
Drop --stat for the full patch, or add --name-status for an A/M/D list. Since both paths are directories, you can append relative pathspecs to limit the comparison, for example -- src.
Comparing JSON Semantically
A minified JSON file and a pretty-printed one with reordered keys can be identical data. git diff --stat still reported "9 insertions(+), 1 deletion(-)" for my two files. Normalize first with jq -S, which sorts keys and pretty-prints:
diff -u <(jq -S . a.json) <(jq -S . b.json)
@@ -1,6 +1,6 @@
{
"env": {
- "LOG_LEVEL": "info",
+ "LOG_LEVEL": "debug",
"REGION": "eu-west-1"
},
"name": "api",
That one line is the only real change. jq -S does not sort arrays, because array order is usually meaningful. If yours isn't, sort them too: jq -S 'walk(if type == "array" then sort else . end)'. For a yes/no answer in CI, jq -n --slurpfile a a.json --slurpfile b b.json '$a == $b' prints true or false, and -e turns that into an exit code. To eyeball a single document first, paste it into the JSON formatter.
Frequently Asked Questions
How do I compare two code files without Git?
Use diff -u file1 file2, which ships with every Linux distribution and macOS. Add -w to ignore whitespace, --strip-trailing-cr for Windows line endings, and -r to compare directories. On Windows without WSL, fc /n file1 file2 or VS Code's code --diff are the built-in options.
What does @@ -12,7 +12,9 @@ mean in a diff?
It's a hunk header. The hunk covers 7 lines of the old file starting at line 12, and 9 lines of the new file starting at line 12. So the change made the region two lines longer. Any text after the closing @@ is function context: the nearest preceding line that looks like a definition.
Which git diff algorithm is best?
For code review, histogram usually produces the most readable output, especially when functions are added, removed or moved. It's fast enough to set globally with git config --global diff.algorithm histogram. myers remains Git's default, and minimal only guarantees the smallest diff, which is not the same as the clearest one.
Can difftastic produce patches I can apply?
No. Difftastic is a display tool. Its output is meant for reading and can't be applied with git apply or patch. Keep Git's normal diff for patches, and use difftastic through git difftool or -c diff.external=difft when you want to understand a change.
How do I ignore formatting changes when comparing code?
For whitespace, use -w or -b with either diff or git diff. For bigger reformatting (line wrapping, brace style), use difftastic, which compares syntax rather than lines. Or run the same formatter (Prettier, Black, gofmt) on both versions first, then diff the formatted outputs.
Conclusion
To compare code reliably, start with git diff --no-index, which works anywhere, and make sure you can read a hunk header. Then remove the noise that hides real changes:
-wor--ignore-cr-at-eolfor whitespace and line endings;jq -Sfor JSON;--diff-algorithm=histogramand--color-movedwhen code moves;- difftastic when a reformat would otherwise drown the actual edit.
Keep delta as your pager, and use VS Code or the browser-based checker when you'd rather see it side by side. Most "this diff is unreadable" problems are really "this diff is comparing the wrong thing" problems.