Git Branch

A branch is simply just a lightweight movable pointer to one of the commits. Whenever we create a repository there is always a default branch created in it with the name master, branches are a part of your everyday development process for example we are planning for a new release in this case we will create a new branch so that it will not impact other existing branch code. Git branches are effectively a pointer to a commit of our changes.

For checking how many branches are there in our github repository, simply execute

git branch

It will show us all the branches that are in our repository, the branch on which we will be active currently will be shown with * in the prefix, example:

* master

It means that currently we are on master branch because it shows a * in the starting

Create a new branch in GIT

To create a new branch in git just execute git branch with the branch name you want to create.

git branch <branch-name>

Now we can see we have two branches created in our local repository, one was master that was created by default and the other one is drillers that we just created.

Checkout a branch in GIT

By default we are on master branch, to checkout to another branch we simply need to execute git checkout followed by the branch name.

git checkout <branch-name>

We can also checkout and create a branch in git with a single command i.e.

git checkout -b <branch-name>

The above command will create a new branch with the name that you have specified and will do checkout too in that particular branch.

Delete a branch in GIT

For deleting a branch in git just use -d flag, -d is for delete

git branch -d <branch name>

Now our branch is deleted from local system, to delete it from remote system we need to push the changes, so we will use

git push origin --delete <branch name>

REMEMBER:- You cannot delete the same branch on which you are currently active, to delete it first checkout to another branch and then delete the branch.

Merging branches in GIT

In an organization there are many developers working on same repository, so not to disturb anyone’s work they create their own branch and start working on that branch, when their job is done they just merge their branch into the main branch ex:- master in our case, and branch that’s need to be merged in drillers

To merge the branch first simply checkout the main branch into which you want to merge your branch, and then you can merge your branch

git checkout master

Now we will merge over branch contents to main branch (master in our demo case), we will use

git merge <branch-name-to-be-merge>

After this the contents of the branch to be merged will be merged into your master branch.

Subscribe Now