✦ You've completed a feature in your project and starting on a new one. You don't want to mess up your fully functional and stable code. You need to build on the previous work, but you want to keep it separate and work carefree on the new feature.
✦ You're working in a team and every team member is working on a separate feature. Everyone needs to work independently.
✦ You're working on something that will take time to complete, in the meanwhile you have to do a bug fix.
That’s where Git branches come in handy! Branches allow you to experiment, develop new features or make changes in isolation without affecting your main codebase.
The master/main branch always contains the fully functional code. We create a new branch to work independently from the main branch. When the work is complete, we merge this branch into the main branch.
Let’s see how simple working with Git branches can be.
Create a New Branch:
git checkout -b feature-branch-name
Create and switch to a new branch.
Flag -b tells we're creating a new branch. The checkout command tells to switch to another branch.
Switch Branches:
git checkout branch-name
Merge Branches:
Once we’ve finished working on a branch, we merge it into our master/main branch with git merge command.
git checkout master
Switch to the master branch
git merge feature-branch-name
Merge changes from feature branch into master branch
Merging branches is also done by Pull Requests.
Delete a Branch:
After merging in the main branch, you can delete a branch.
git branch -d feature-branch-name
Common Categories of Git Branches
Git branches can be categorized based on their purpose, though the process to create them is always the same using the git checkout command.
Feature Branches: Used to develop new features.
Bugfix Branches: Used to fix specific bugs or issues.
Release Branches: Used to prepare for a major release.
Hotfix Branches: Used for urgent fixes to critical bugs in production.
We can prefix these categories in branch name (as per git branch naming conventions) to easily identify them. e.g. feature/add-login-page, bugfix/dashboard-display-error
Working with branches can improve the development process, keep the workflow smooth and maintain clean history in version control.
Top comments (2)
Simplified even for absolute beginners. Great work.
Thanks @simeondee for your kind words. I tried to make it as simple as possible for beginners.