How To Use Branches Within Git

In this article we’ll look at how to use branches within Git and how using the different branches of development can help benefit a team of developers working on a single project simultaneously.

By default, Git comes with a master branch. This is seen as the main line of workflow. This can be seen by running the following command within your repository.

$ git branch

You will see something like this:

* master

The asterisk indicates that this is the branch you are currently on at the moment.

To create a new branch, run the following command.

$ git branch some-change

When running the git branch command again, you’ll be able to see both the master and some-change branches.

* master

To switch to the branch, you can run the checkout command.

$ git checkout some-change
Switched to branch 'some-change'

This will switch the branch to ‘some-change’ and therefore will move the asterisk to point to the new branch.

You can create a branch and switch to it using just one command.

$ git checkout -b some-change

When committing your development changes and are ready to push them to the remote repository, use the push command specifying the branch.

$ git push -u origin some-change

It is common on development environments to be on different branches in order to test development changes. Therefore to pull down the branch from the remote repository to another repository, whether it be a development environment, or a local repository on another machine, use the following.

$ git pull origin some-change

When changes have been thoroughly tested and are ready to merge back into the master branch, checkout to the master branch and use the merge command to merge the ‘some-change’ branch into master.

$ git checkout master
Switched to branch 'master'
$ git merge some-change

Then push the master branch to update the remote repository.

$ git push -u origin master

Now that the development changes have been merged into the master branch, you may find that your created branch is no longer needed. You can delete the branch by running:

$ git branch -d some-change

By doing this, you will not lose any history of the changes made. Git also will detect whether the branch has been merged into master, and if it hasn’t, will provide a warning message when attempting to delete the branch.

error: The branch 'some-change' is not fully merged.
If you are sure you want to delete it, run 'git branch -D some-change'.

As the message mentions, you can also use -D (instead of -d), to force delete a branch should you need to.

This branching feature is very simple to test out development changes without worrying about destroying the initial code base, and is one of the features that makes Git so powerful.