How to see the differences between 2 branches in git

You have been working on a feature branch for a while, and you want to see the differences between that branch and the main branch. How do you do that?

Let’s say you have two branches: main and b1.

For the purpose of this article, these branches contain four text files: file[1-4].txt.

On main, the content of these files is:

FileContent
file1.txt1.main
file2.txt2.main
file3.txt3.main
file4.txtdoes not exist on that branch

On b1, the content of these files is:

FileContent
file1.txt1.main
file2.txtwas deleted on that branch
file3.txt3.main
3.b1
file4.txt4.b1

Let’s assume you are currently on the main branch and want to see the differences between main and b1 branches.

You can start with the git diff --name-status command, which will show you the names of the files that are different between the two branches.

alina

alina git:( main ) git diff --name-status main..b1

D       file2.txt

M       file3.txt

A       file4.txt

alina git:( main )

The output indicates:

  • file2.txt was deleted (D) on the b1 branch
  • file3.txt was modified (M) on the b1 branch
  • file4.txt was added (A) on the b1 branch

If you want to see the actual changes, you can use the git diff command without any options.

alina

alina git:( main ) git diff main..b1

diff --git a/file2.txt b/file2.txt

deleted file mode 100644

index 753f791..0000000

--- a/file2.txt

+++ /dev/null

@@ -1 +0,0 @@

-2.main

diff --git a/file3.txt b/file3.txt

index 2e04e7d..e541778 100644

--- a/file3.txt

+++ b/file3.txt

@@ -1 +1,2 @@

 3.main

+3.b1

diff --git a/file4.txt b/file4.txt

new file mode 100644

index 0000000..1981cd0

--- /dev/null

+++ b/file4.txt

@@ -0,0 +1 @@

+4.b1

alina git:( main )

The output is a bit difficult to read, but it provides the same information.

You can be more specific and ask git to show you the changes for a specific file.

Since you know that file3.txt was modified on the b1 branch, you can request git to show you the changes for that file.

alina

alina git:( main ) git diff main..b1 -- file3.txt

diff --git a/file3.txt b/file3.txt

index 2e04e7d..e541778 100644

--- a/file3.txt

+++ b/file3.txt

@@ -1 +1,2 @@

 3.main

+3.b1

alina git:( main )

Another command you can use is git diff b1:file3.txt file3.txt, which produces the same output.

For the file file4.txt, which was added on the b1 branch, you can ask git to show you the changes for that file.

alina

alina git:( main ) git diff main..b1 -- file4.txt

diff --git a/file4.txt b/file4.txt

new file mode 100644

index 0000000..1981cd0

--- /dev/null

+++ b/file4.txt

@@ -0,0 +1 @@

+4.b1

alina git:( main )

Alternatively, you can simply ask git to show you the content of that file using git show:

alina

alina git:( main ) git show b1:file4.txt

4.b1

alina git:( main )