Git and GitHub course menu
git diff Explained: How to See What Changed
Compare your work with git diff, see staged changes with --staged, compare commits and branches, and learn to read diff output line by line.
On this page
git status tells you which files changed. git diff tells you what changed inside them. Reading a diff before every commit is one of the best habits you can build.
See unstaged changes#
Here notes.txt has three lines. Change the second and add a fourth:
cat notes.txtBuy milk
Call the bank
Pay rentsed -i 's/Call the bank/Call the bank before 5 pm/' notes.txt
echo "Water the plants" >> notes.txt
git diffdiff --git a/notes.txt b/notes.txt
index 62e4899..a7233bc 100644
--- a/notes.txt
+++ b/notes.txt
@@ -1,3 +1,4 @@
Buy milk
-Call the bank
+Call the bank before 5 pm
Pay rent
+Water the plantsReading the output#
Git has no idea of an edited line: a changed line appears as one removed line and one added line.
Staged changes#
After git add, plain git diff shows nothing, because it compares your files with the staging area:
git add notes.txt
git diff
git diff --stageddiff --git a/notes.txt b/notes.txt
index 62e4899..a7233bc 100644
--- a/notes.txt
+++ b/notes.txt
@@ -1,3 +1,4 @@
Buy milk
-Call the bank
+Call the bank before 5 pm
Pay rent
+Water the plantsgit diff --staged compares the staging area with the last commit, so it shows exactly what the next commit will contain. Run it before committing.
Compare commits#
Give two commits, and Git shows the changes from the first to the second:
git diff HEAD~1 HEAD --stat notes.txt | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)--stat shows a summary instead of every line. --name-only lists only the file names.
Compare branches#
The same works with branch names, which is how you review a feature before merging:
git diff main feature/login
git diff main...feature/loginWith three dots, Git shows only what feature/login changed since it split off from main, which is usually what you want. This is also what a pull request shows.
Compare one word at a time#
For long lines of text, this highlights just the words that changed:
sed -i 's/before 5 pm/before 4 pm/' notes.txt
git diff --word-diffdiff --git a/notes.txt b/notes.txt
index a7233bc..d205443 100644
--- a/notes.txt
+++ b/notes.txt
@@ -1,4 +1,4 @@
Buy milk
Call the bank before [-5-]{+4+} pm
Pay rent
Water the plantsCommon mistakes#
Practice#
Practice exercise
Add the line Book tickets to notes.txt and stage it. Then show only the staged change as a summary with --stat.
Show solution
echo "Book tickets" >> notes.txt
git add notes.txt
git diff --staged --stat notes.txt | 1 +
1 file changed, 1 insertion(+)Key takeaway#
Finished this lesson?