Table of contents
Git Diff
We can use the
git diff
command to view changes between commits, branches, files, our working directory, and more!We often use git diff alongside commands like git status and git log, to get a better picture of a repository and how it has changed over time.
Without additional options,
git diff
lists all the changes in our working directory that are NOT staged for the next commit.git diff --staged
will list the changes between the staging area and our last commit. You can think of it as "Show me what will be included in my commit if I run git commit right now"git diff HEAD
lists all changes in the working tree since your last commit. It compares the HEAD and the working directory and shows both staged and unstaged changes.git diff branch1..branch2
will list the changes between the tips of branch1 and branch2. The order matters as the first branch is referred to as File A and second as File B.To compare two commits, provide git diff with the commit hashes of the commits in question in the form of
git diff commit1..commit2
We can also view the changes within a specific file by providing git diff with a filename.
git diff HEAD [filename] git diff --staged [filename]
Reading Git Diffs
For each comparison, Git explains which files it is comparing. Usually, this is two versions of the same file.
Git also declares one file as "A"(old) and the other as "B"(new).
Markers
File A and File B are each assigned a symbol.
Changes in File A are indicated with a minus sign (-)
Changes in File B are indicated with a plus sign (+)
Chunks
A diff won't show the entire contents of a file, but instead only shows portions or "chunks" that were modified.
A chunk also includes some unchanged lines before and after a change to provide some context
Each chunk starts with a chunk header, found between @@ and @@.
There are two sets of numbers in the chunk. One set belongs to File A and the other belongs to File B, that is what the sign indicates
The number with the sign indicates from which line no, the lines are extracted from and the second number indicates how many lines have been extracted.
From file a, 4 lines are extracted starting from line 3.
From file b, 5 lines are extracted starting from line 3
Changes
Every line that changed between the two files is marked with either a + or - symbol and lines without any sign exist in both files
Simply the - can be interpreted as removed and + as added.
lines that begin with - come from file A
lines that begin with + come from file B
diff --git a/rainbow.txt b/rainbow.txt
index 72d1d5a..f2c8117 100644
--- a/rainbow.txt
+++ b/rainbow.txt
@@ -3,4 +3,5 @@ orange
yellow
green
blue
-purple
+indigo
+violet