Compare files · Git

How to Diff Two Files with Git

git diff compares far more than uncommitted changes. It can compare any two versions of a file, and, with one flag, any two files that are not in a repository at all.

Your working copy against the last commit

Plain git diff shows unstaged changes; git diff --staged shows what is about to be committed; git diff HEAD shows both together. Add a path to limit the output to one file.

$ git diff -- src/app.js
$ git diff --staged -- src/app.js
$ git diff HEAD~3 -- src/app.js   # against three commits ago

The same file in two branches or commits

Name both revisions, then the path. Two dots compare the tips; three dots compare the second against the common ancestor, which is what a pull request shows.

$ git diff main..feature -- config/app.yaml
$ git diff main...feature -- config/app.yaml
$ git diff a1b2c3d 9f8e7d6 -- README.md

Two files that are not in Git at all

--no-index turns git diff into a general-purpose diff with Git's colouring and pager, for any two paths on disk.

$ git diff --no-index app.conf app.conf.new

Word-level and statistics

--word-diff or --color-words highlights changed words instead of whole lines, which is far more readable for prose and long lines. --stat summarises how many lines changed per file, and -w ignores whitespace.

$ git diff --color-words -- docs/guide.md
$ git diff --stat main..feature

Open the diff in a visual tool

git difftool launches your configured tool (VS Code, meld, Beyond Compare) for each changed file. Set it once with git config --global diff.tool vscode and the matching difftool.vscode.cmd, then git difftool works everywhere git diff does.

$ git config --global diff.tool vscode
$ git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'
$ git difftool main..feature -- src/app.js
Compare two texts online Paste both versions. Runs in your browser, nothing is uploaded.

FAQ

How do I see the difference between two commits for one file?

git diff <commitA> <commitB> -- path/to/file. Use git log --oneline -- path/to/file to find the commit ids.

Why is git diff empty when the file changed?

The change is probably staged; use git diff --staged. If the file is new and untracked, git does not diff it until it is added; git diff --no-index /dev/null newfile shows it.

Can I diff a file against the clipboard?

Not with git alone. Paste the clipboard text next to the file's contents in the online diff checker, or use VS Code's Compare Active File With Clipboard.