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
$ 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).
$ 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
$ git diff HEAD –stat
drinks.txt | 1 +
1 file changed, 1 insertion(+)
Compare two commits
$ 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
| Option | What it does |
|---|---|
--stat | Short summary with file names and number of lines changed |
--name-only | Only the names of changed files |
--name-status | File names with the status (A, M, D) |
-w | Ignore the white space changes |
--color-words | Show the changed words instead of full lines |
$ 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.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |