Git branch mechanism is important part of the code versioning. We can create new branches in order to make same source available multiple development paths. In this tutorial we will learn how to create and manage new branch with Git.
We will start by listing current existing branches. We will use
git branch command without any option or parameter. Branch which prefixed with
* is the current working or active branch.
$ git branch
Create Local Branch and Switch This Branch
We can create a local branch with different commands
We will use
branch command and provide the branch name
test in this example.
$ git branch test
We will use
checkout command with
-b option and branch name. This will also automatically change current branch to the newly created branch. In this example we will create branch named
$ git checkout -b silver
We can see the message
Switched to a new branch 'silver'.
Change Working Branch
If we just want to change current working or active branch we can use
checkout command. We will also provide the branch name we want to change. In this example we will change branch
$ git checkout newversion
Add New Remote Repository For Current Branch
Git is mainly designed to be used in a distributed manner. So there will be a lot of remote Git repositories and branches. We can add new remote branch for the current branch with the
remote add command. In this example we will add remote system github.com new branch named
$ git remote add github.com/ibaydan test
Update Branch From Remote Repository
Git remote branches can be updates frequently where our local branch may be outdated. We can update our local branch from remote repository branch with the
fetch command like below. We will update local branch from remote named
$ git fetch github.com/ibaydan
Delete Local Branch
After completing changes and merged to the main branch we may need to delete local branch. we will use
branch command with
-d means delete. We will delete local branch named
silver in this example.
$ git branch -d silver
Force Delete Local Branch
If there are some problems for normal removal or deletion of the local branch we can force delete operation. We will use
-D option for forcing deletion. In this example we will delete branch named
$ git branch -D silver