Git branches are powerful tools for managing feature development, bug fixes, and code collaboration. Whether you’re working solo or on a team, knowing how to switch between branches in Git is a fundamental skill.
In this blog post, we’ll walk through how to view, switch, and manage branches in Git using the command line.
π What Is a Git Branch?
A branch in Git is a lightweight, movable pointer to a specific commit. You can use branches to:
- Develop features in isolation
- Test experimental ideas
- Collaborate without affecting the main codebase
The default branch in Git is usually called main
or master
.
π How to Change (Switch) Branches
β 1. Check Your Current Branch
To see the branch youβre currently on:
git branch
The active branch will be highlighted with an asterisk *
.
π 2. Switch to an Existing Branch
Use the git checkout
or git switch
command:
git checkout branch-name
# or (modern Git versions)
git switch branch-name
π Example:
git checkout feature/login
Note:
git switch
was introduced in Git 2.23 as a more intuitive alternative togit checkout
.
π§ͺ 3. Create and Switch to a New Branch
To create a new branch and switch to it in one step:
git checkout -b new-branch
# or
git switch -c new-branch
π Example:
git switch -c feature/payment-gateway
β οΈ Important Notes
- Uncommitted changes: Git may prevent you from switching branches if you have uncommitted changes that conflict with the branch youβre switching to. To resolve this:
- Commit your changes
- Stash your changes:
git stash
- Or discard them:
git restore .
π Summary of Common Branch Commands
Task | Command |
---|---|
List all branches | git branch |
Switch to a branch | git switch branch-name |
Create and switch to new branch | git switch -c new-branch |
Create a new branch (stay put) | git branch new-branch |
Delete a branch | git branch -d branch-name |
Stash changes before switching | git stash |
π§ Final Thoughts
Branching is one of Gitβs most powerful features. Mastering how to switch between branches helps keep your workflow clean, efficient, and collaborative. Whether you’re building features, fixing bugs, or reviewing code, being comfortable with branches is essential.