How to use the Git command git diff
The git diff
is used to show differences between commits, branches, files, and more. This guide will cover the basics in addition to showing more advanced use cases of git diff
.
**Basic usage of git diff
Viewing unstaged changes:
To see what changes have been made locally but haven’t yet been staged for commit, run:
git diff
For example, this is what running
git diff
would look like after we update a Dockerfile to include a new base image, in addition to updating the readme to record the change.
In this instance, the
git diff
command is showing us the difference between our local files and the state of those same files in the most recent commit.Viewing staged changes:
To see what changes are staged for the next commit (i.e., after
git add
but beforegit commit
) run:git diff --staged
Alternatively, you can use
git diff --cached
, as both-staged
and-cached
flags serve the same purpose.
After staging our changes from the previous step with git add
we can now see them by running git diff --staged
Comparing files and commits
Diff of a specific file:
To view changes in a specific file run:
git diff <file-path>
Between two commits:
To see the differences between two commits:
git diff <commit-id-1> <commit-id-2>
Between two files across commits:
For comparing the same file across two different commits:
git diff <commit-id-1>:<file-path> <commit-id-2>:<file-path>
Summary of changes:
To get a short summary of which files changed, and the amount of additions/deletions per file, run:
git diff --stat
Diff between branches
Comparing branches:
To compare the current branch with another branch:
git diff <branch-name>
Diff Between specific branches:
To compare two specific branches:
git diff <branch-name-1>..<branch-name-2>
Working with git diff
output
Exporting diff to a file:
To save the output of a diff to a file:
git diff > diff_output.txt
Troubleshooting and tips
git diff
shows no output:- If
git diff
doesn't show any output, it could mean either there are no changes between the compared entities, or you might be comparing the same commit or branch against itself.
- If
Understanding the output:
Lines added in the diff are prefixed with a
+
and shown in green.Lines removed are prefixed with a
-
and shown in red.
Using
git diff
in GUI tools:- Many graphical Git clients and IDEs integrate
git diff
functionality, providing a more user-friendly interface to review changes.
- Many graphical Git clients and IDEs integrate
For further reading please see the official git documentation.