Version control with Git allows developers to work on multiple features or fixes simultaneously through branches. Whether you’re moving from the main
branch to a feature branch or switching back to continue another task, Git makes it simple to manage branches using the terminal.
In this blog post, we’ll walk you through how to switch branches in Git effectively and safely.
β What Is a Git Branch?
A branch in Git represents an independent line of development. It allows multiple developers (or one developer with multiple ideas) to work on different tasks without affecting the main codebase.
Common examples:
main
ormaster
β the production-ready branchfeature/login
β a new feature branchbugfix/header
β a branch fixing an issue
π How to Switch Branches in Git
To switch branches in Git, use the git switch
or git checkout
command.
πΉ Method 1: Using git switch
(Recommended)
git switch branch-name
Example:
git switch feature/login
If the branch doesnβt exist yet, you can create and switch at once:
git switch -c new-branch-name
πΉ Method 2: Using git checkout
(Legacy/Still Common)
git checkout branch-name
This is the older way and still widely used.
π Step-by-Step: Switching Branches
1. List All Branches
git branch
- Shows a list of local branches.
- The current branch is marked with
*
.
To see remote branches:
git branch -a
2. Switch to an Existing Branch
git switch <branch-name>
Or:
git checkout <branch-name>
If the branch exists, Git will switch to it and update your working directory.
3. Create and Switch to a New Branch
git switch -c <new-branch-name>
Or:
git checkout -b <new-branch-name>
This creates a new branch from the current HEAD and switches to it.
β οΈ Important Tips
- Make sure your working directory is clean (no uncommitted changes) before switching branches.
- Use
git stash
to temporarily save uncommitted changes:git stash git switch other-branch
- You can retrieve stashed changes later with
git stash pop
.
β Summary
Task | Command |
---|---|
List all branches | git branch |
Switch to a branch (modern) | git switch branch-name |
Switch to a branch (legacy) | git checkout branch-name |
Create and switch to new branch | git switch -c new-branch |
Save changes before switching | git stash |
π Final Thoughts
Switching branches in Git is a core workflow that enables safe, efficient, and parallel development. Whether you’re creating a new feature or reviewing code from a teammate, understanding how to navigate branches from the command line gives you complete control over your project history.