Git Branches
Git branches are used to develop features, fix bugs, and experiment with new ideas. They allow you to split up development work and manage different lines of development in parallel.Creating Branches
Creating a new branch is simple and allows you to work on features in isolation.Create a New Branch
Usegit checkout -b <branch> to create a new branch with the specified name and switch to it:
git branch <branch> and then git checkout <branch> separately.
Create an Empty Branch
If you want to create an empty branch without any history, usegit checkout --orphan <branch>:
Switching Branches
You can easily switch between branches usinggit checkout or the newer git switch command.
Switch to an Existing Branch
Switch to the Previous Branch
Use- as a shorthand for the previous branch:
Viewing Branches
List all branches in your repository:Merging Branches
At some point, you’ll want to merge a branch into another branch, usuallymaster or main.
Basic Merge
Switch to the target branch first, then merge the source branch:Creating a Merge Commit
If you want to create a merge commit, use the--no-ff flag:
Deleting Branches
As your project progresses, you may accumulate branches that are no longer needed. Deleting these branches keeps your repository clean and organized.Delete Local Branch
Usegit branch -d <branch> to delete a local branch:
Delete Remote Branch
Usegit push -d <remote> <branch> to delete a remote branch:
Delete Detached Branches
Detached branches are branches that are not associated with any commit. Usegit fetch --all --prune to garbage collect them:
Delete Merged Branches
You can delete all branches that have been merged into a target branch:Branch Workflows
Feature Branch Workflow
Bugfix Workflow
Best Practices
- Use descriptive branch names (e.g.,
feature/user-auth,bugfix/login-error) - Keep branches focused on a single feature or fix
- Regularly merge or rebase with the main branch to avoid conflicts
- Delete branches after they’ve been merged
- Use merge commits (
--no-ff) for feature branches to preserve history - Create branches from an up-to-date main branch