Run git diff branch1 branch2
In the previous step, we used git log
to see which commits were present in different parts of our history. Now, let's use the git diff
command to see the actual changes between two different points in time or between different branches. This is like comparing two versions of your time machine and seeing exactly what parts were added, removed, or modified.
First, ensure you are in your project directory:
cd ~/project/my-time-machine
We currently only have one branch, master
. To demonstrate comparing branches, let's create a new branch called feature-branch
. Think of a branch as an alternate timeline where you can work on new features or experiments without affecting the main timeline (master
).
git branch feature-branch
Now, let's switch to our new branch:
git checkout feature-branch
You should see output indicating you've switched branches:
Switched to branch 'feature-branch'
On this new branch, let's make a change to our message.txt
file:
echo "Adding a line on the feature branch." >> message.txt
This command appends a new line to the message.txt
file.
Now, let's commit this change on the feature-branch
:
git add message.txt
git commit -m "Add a line to message.txt on feature branch"
You should see output similar to this after the commit:
[feature-branch a1b2c3d] Add a line to message.txt on feature branch
1 file changed, 1 insertion(+)
Now we have two branches (master
and feature-branch
) with different commit histories. The master
branch has the first two commits, and the feature-branch
has those two commits plus the new commit we just made.
Let's use git diff
to see the differences between the master
branch and the feature-branch
.
git diff master feature-branch
The output will show you the exact lines that are different between the two branches:
diff --git a/message.txt b/message.txt
index a1b2c3d..e4f5g6h 100644
--- a/message.txt
+++ b/message.txt
@@ -1 +1,2 @@
Hello, Future Me
+Adding a line on the feature branch.
This output shows that the message.txt
file is different. The line starting with +
indicates a line that was added on the feature-branch
compared to the master
branch.
Using git diff
is incredibly powerful for understanding exactly what changes have been made between different versions of your project or between different branches. It helps you review changes before merging them and pinpoint where specific modifications occurred.
Press q
to exit the diff view and return to the command line.