Git tutorial 2 ( Git Branching )

In our previous tutorial , we have learnt basics of git and how to create, commit and push to git . In this tutorial, we will learn about “Branching” and some other useful commands .

 

What is Git Branching :

Git doesn’t store only the new changes, but it stores a snapshot of the data on each commit. One commit object is created that contains a pointer to the snapshot of the content. If you have made 3 commits on the same branch, it looks something like below :

 

git-2-image1

 

Ok…so what is Git branching ?? Branch is simply a lightweight movable pointer to one of these commits. Default branch name is “master” in git. Everytime we commit new changes, it moves to the latest.

git-2-image2

 How does git know on which branch we are currently on ?? It keeps a pointer “HEAD” , that moves automatically if we checkout new branch.

git-2-image3

Let’s create one new branch “test”.

$ git branch test
 Currently we have two branches “master” and “testing” and we are on “master” . So HEAD will point to the “master” branch :

git-2-image4

 

 Checkout to branch “test” :

$ git checkout test
Now “HEAD” will point to the “testing” branch.

git-2-image5

 

Commit one new change on this “test” branch . ( As discussed in our previous tutorial)
 
Final view will be like :

git-2-image6

Now we have two branches “master” ,”test” and we have different commits on both of these branches.

In our last step, we will checkout back to the “master” branch, merge all changes from “test” branch to the master and finally delete this “test” branch.

//checkout back to master branch
$ git checkout master

//Merge changes in master: 
$ git checkout master
$ git merge test
 
//Delete test branch:
$ git branch -d hotfix

Some useful Commands :
//Check branch and branch pointers
$ git log --oneline --decorate

//To check history of commits from different branches
$ git log --oneline --decorate --graph --all

//To create a branch and switch to it at the same time
$ git checkout -b test

//This is shorthand for
$ git branch test 
$ git checkout test

 

Leave a Reply