Branches in Git
Branches are a core feature of Git that allow you to work on different versions of your code simultaneously.
What are Branches?
A branch in Git is essentially a lightweight movable pointer to a commit. The default branch is usually called main or master.
Why Use Branches?
Branches allow you to:
- Work on features without affecting the main codebase
- Experiment with new ideas safely
- Collaborate with team members
- Maintain multiple versions of your project
Creating Branches
Create a New Branch
git branch feature-branch
Switch to a Branch
git checkout feature-branch
Or use the newer command:
git switch feature-branch
Create and Switch in One Command
git checkout -b feature-branch
Or:
git switch -c feature-branch
Working with Branches
List All Branches
git branch
The current branch will be marked with an asterisk (*).
List Remote Branches
git branch -r
List All Branches (Local and Remote)
git branch -a
Merging Branches
Merge a Branch into Current Branch
git merge feature-branch
Merge Strategies
Git offers several merge strategies:
- Fast-forward merge: When there are no conflicts
- Three-way merge: When branches have diverged
- Squash merge: Combines all commits into one
Deleting Branches
Delete a Local Branch
git branch -d feature-branch
Force delete (if branch hasn’t been merged):
git branch -D feature-branch
Delete a Remote Branch
git push origin --delete feature-branch
Best Practices
- Use descriptive branch names:
feature/user-authenticationis better thanbranch1 - Keep branches short-lived: Merge or delete branches regularly
- Use a branching strategy: Git Flow, GitHub Flow, or GitLab Flow
- Protect main branch: Use branch protection rules on GitHub
Common Branching Workflows
Feature Branch Workflow
- Create a feature branch from main
- Make changes and commit
- Push branch to remote
- Create a pull request
- Review and merge
Git Flow
A more structured approach with:
main: Production-ready codedevelop: Integration branchfeature/*: New featuresrelease/*: Preparing releaseshotfix/*: Emergency fixes