Git Branching Basics
Git branching is the core feature that allows Git to support parallel development. Branches let you work on features, fixes, or experiments without breaking the main codebase.
This guide explains what a branch is, how to create, list, switch, merge, and rebase branches, and which workflows are safe for everyday development.
What is a branch in Git?
A Git branch is a lightweight pointer to a commit. When you create a new branch, Git does not copy files — it simply creates a new pointer that moves forward as you make commits.
Key ideas:
- The default branch is usually called
main - Each branch represents an independent line of development
- Commits belong to the branch that was checked out when they were created
- Branches are cheap and fast to create
Common branch types
feature/<name>– new featuresfix/<issue>– bug fixeschore/<task>– refactoring or maintenancerelease/<version>– release preparation
Short-lived, focused branches are easier to review and merge.
Creating and switching branches
Create a new branch and switch to it
git checkout -b feature/add-login
(Equivalent to git branch feature/add-login + git checkout feature/add-login.)
Switch branches
git checkout main
Check current branch
git branch --show-current
Listing branches
List local branches
git branch
List all branches (local + remote)
git branch -a
Committing and pushing a branch
git add .
git commit -m "Add basic login flow"
git push -u origin feature/add-login
The -u flag sets the upstream so future pushes work with git push.
Merging branches
To merge a feature branch into main:
git checkout main
git pull origin main
git merge feature/add-login
This may:
- Fast-forward (no merge commit), or
- Create a merge commit if histories diverged
Rebase vs merge (important)
What is git rebase?
Rebasing moves your commits onto a new base commit, creating a linear history.
git checkout feature/add-login
git rebase main
When to use rebase
- To clean up private branches
- To keep history linear before opening a PR
Resolving merge conflicts
If Git reports conflicts:
git merge feature/add-login
# fix files manually
git add conflicted-file
git commit
Conflicts happen when the same lines were changed on both branches.
Best practices
- Create a branch for every non-trivial change
- Keep branches short-lived
- Merge
maininto your branch regularly - Prefer merge for shared branches
- Rebase only local, private branches
- Delete branches after merge
Common mistakes
- Committing directly to
main - Rebasing public branches
- Forgetting to pull before merging
- Losing work by deleting unmerged branches
- Pushing to the wrong branch
Key takeaways
- A branch is a pointer, not a copy
- Use branches to isolate work safely
git branch,git checkout,git merge, andgit rebasecover most workflows- Merge for shared history, rebase for private cleanup
- Push branches early for CI and review