Creating Branches in Git | The Git Checkout Command
In this article, you will learn about branches in Git and how to create new branches.
What is a branch?
In Git you are working on branches. You can create, switch between, and delete branches. The default branch name in Git is master. The repository in which you are working will contain other branches, too. Often you have a branch called development (or develop) and several other branches which can be named after features or after IDs of features etc. There is no specific schema to name branches except the two common branch names development and master.
When you are working on a branch locally and push the first time to the server, a branch with the same name as you named it locally will be created on the server. This means you have the same branch two times: locally and remotely.
When others want to work on the branch you worked on locally, they can simply checkout this branch from the remote server. This will create a branch with the same name and the same content as the branch on the remote server on their machine. Of course, they will only be able to checkout the revision you pushed most recently to the server and not what you might have added locally, meanwhile. In case that you continue working on your local branch and push changes to the server, your teammates have to pull the latest revision to update their local branch with your latest changes.
What is a protected branch?
A protected branch is a branch to which you cannot push. The development and master branches should be protected branches to avoid inconsistencies which might create merge conflicts. Another reason for using protected branches is that there may be teammates/people who abuse an unprotected development or master branch to push to them without following your process, e.g. code reviews or checking test coverage before merging.
How can I create a new branch?
In case that you don’t have the desired branch on your machine and assuming you want to create a branch called “featureXYZ”, you can use the branch command to create a new branch:
git branch featureXYZ
To check out this branch, you need to use the checkout command:
git checkout featureXYZ
In case that you want to create a branch and check it out immediately, you can use the checkout command using the -b flag:
git checkout -b featureXYZ
In both cases, the branch featureXYZ will be created locally but not on the server. It will be created on the server when you are performing your first push to the server. How can I create a new branch from an already existing remote branch?
Let’s assume that you have a remote branch called “featureA” and you want to have a local branch of it, you can simply use the checkout command without the -b flag:
git checkout featureA
In case that there is no remote branch called “featureA”, Git will let you know. It may be possible that you have a typo in the branch name or that it really does not exist.