Git Diff

The git diff command shows the exact lines which are changed. You can compare your working files, the staging area, two commits or two branches.

Syntax

git diff
git diff --staged
git diff HEAD
git diff <commit1> <commit2>
git diff <branch1> <branch2>

Prepare an example

Changes not staged yet

Terminal output

$ printf "Tea\nGreen Tea\nCoffee\nJuice\n" > drinks.txt
$ git diff
diff –git a/drinks.txt b/drinks.txt
index 8b97f1e..ba06eac 100644
— a/drinks.txt
+++ b/drinks.txt
@@ -1,3 +1,4 @@
Tea
+Green Tea
Coffee
Juice

How to read it: lines with - are removed, lines with + are added, and the @@ line tells the position in the file.

Changes in the staging area

After git add, the plain git diff shows nothing. To compare the staged changes with the last commit, use --staged (or --cached).

Terminal output

$ git add drinks.txt
$ git diff
$ git diff –staged
diff –git a/drinks.txt b/drinks.txt
index 8b97f1e..ba06eac 100644
— a/drinks.txt
+++ b/drinks.txt
@@ -1,3 +1,4 @@
Tea
+Green Tea
Coffee
Juice

All changes since the last commit

Terminal output

$ git diff HEAD –stat
drinks.txt | 1 +
1 file changed, 1 insertion(+)

Compare two commits

Terminal output

$ git commit -q -m "Add green tea"
$ git diff HEAD~1 HEAD
diff –git a/drinks.txt b/drinks.txt
index 8b97f1e..ba06eac 100644
— a/drinks.txt
+++ b/drinks.txt
@@ -1,3 +1,4 @@
Tea
+Green Tea
Coffee
Juice

HEAD~1 means one commit before HEAD.

Useful options

OptionWhat it does
--statShort summary with file names and number of lines changed
--name-onlyOnly the names of changed files
--name-statusFile names with the status (A, M, D)
-wIgnore the white space changes
--color-wordsShow the changed words instead of full lines
Terminal output

$ git diff HEAD~1 HEAD –name-status
M drinks.txt

Compare two branches

git diff main feature-login
git diff main...feature-login

Two dots show the difference between the tips of the branches. Three dots show the changes of the second branch since it was split from the first one, which is usually what you want before a merge.

Note: A good habit: run git diff before git add, and git diff --staged before git commit. You will catch many small mistakes. Next: Git Ignore.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.