Friday, September 3, 2021

Howto compare 2 GIT branch

 The benefits of GIT is being able to work in different branches from the master codebase. Commonly a new feature being developed would be published to a new branch for review before being merged to the master branch. Once it is merged to the master branch, the new branch would be removed from the remote site.

Before merge to the master branch, it is possible to compare between the 2 branches. This will allow a check on files changes and where are the code changes. Here, lets see how to retrieve the new branch from remote, then compare changes made. The git command format in general would be;

git option <arguments>


  • code base is in the branch master
  • remote name is origin
  • new remote branch is FEATURE
  • git version 1.8 and 2.19

Retrieve a remote branch

This section is more of a recap where the remote branch does not exist on your local machine. The option branch can use -b or -t depending on your needs. There is the example with -t where it creates the required branch locally and fetch its contents from remote.

git branch -t origin/FEATURE

git checkout FEATURE

View latest commit in the branch

git log

git log --oneline

Compare difference between branch

git diff master..FEATURE

View only the files that changed

git diff --name-status master..FEATURE

This describes use with TWO dots in the diff option. There is a THREE dots with the diff, but display results that compares the common between the 2 branches. More commonly, in cases that feature is already merged to master, it will produce no results.

Compare difference between commits

Displaying differences in commit between branches is ideal to identify developer notes in the commit between branches at level of commits.

git log master..FEATURE

There are many options to display log difference. Here is one example

git log --oneline --graph --decorate --abbrev-commit master..FEATURE

Compare difference in a file

When working to identify where a specific file has changed between two branches, just mention the relative path of the file

git diff master..FEATURE -- public/js/app.js

Compare with difftool

Here is an option to launch external editors to view the diff results. 

git difftool master..FEATURE

If required, a full directory diff can be done by adding the argument -d. This works fine on our linux systems, but on a GUI environment, the graphical code editors can be configured and activated with the argument -g.

Thats the basics to compare two branches using the diff and log options. Comparing existing branch or commits can be done with shorthand notations, which is much easier and I did not mention them here. This will help to ensure a smoother management of source codes.

No comments:

Blog Archive