How would you use git diff to see the differences between two branches?

git diff is a powerful command in the Git version control system that shows changes between commits, commit and working tree, etc. To see the differences between two branches, you can use it in the following way.

The general syntax of the command is:

git diff <branch1>..<branch2>

Where <branch1> and <branch2> are the names of the branches you want to compare.

Detailed Steps

  1. Open Terminal or Git Bash

First, you’ll need to open a terminal window (or Git Bash on Windows) to run these commands.

  1. Navigate to your repository

Use the cd command to navigate to the directory that contains your Git repository.

cd /path/to/your/repository
  1. Check available branches

Before comparing, it is good to check available branches in your repository. You can use the command git branch to list all of the branches.

git branch

This will list all the branches in your repository, and the branch you are currently on will be indicated with an asterisk (*).

  1. Compare the branches

If you want to see the differences between branch1 and branch2, you can run:

git diff branch1..branch2

This will show you the differences between the tip (latest commit) of branch1 and branch2.

If you want to see the differences between branch2 and branch1, simply reverse the branches:

git diff branch2..branch1

This will output a list of changes between the two branches. Additions will be marked with a + and shown in green, and deletions will be marked with a - and shown in red.

  1. Understand the output

The output of the git diff command can be quite verbose. It’s important to know that lines added are shown with a + and lines removed are shown with a -. The changes are shown in a unified diff format, a standard format for displaying differences between files.

Here is a brief look at how it is structured:

diff --git a/file1 b/file2
index 1234..5678 7890
--- a/file1
+++ b/file2
@@ -1,6 +1,6 @@
-line 1 of file1
-line 2 of file1
-line 3 of file1
+line 1 of file2
+line 2 of file2
+line 3 of file2
  1. Use a Graphical Interface (optional)

If you find it difficult to understand the command-line output, there are also many graphical tools available for showing diffs between branches. These tools can provide a more user-friendly and visual representation of the differences.

Some of these tools are built into code editors (like VS Code or Atom), others are standalone apps (like Sourcetree or GitKraken), and some are web-based tools provided by online code hosting services (like GitHub, Bitbucket, or GitLab).

In general, the git diff command is a powerful tool for understanding the changes that have happened between different branches, commits, or the working tree and the index. By mastering it, you will be able to navigate and understand your project’s history more effectively.