How to Change Branches in Git: A Complete Guide

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 to git 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

TaskCommand
List all branchesgit branch
Switch to a branchgit switch branch-name
Create and switch to new branchgit switch -c new-branch
Create a new branch (stay put)git branch new-branch
Delete a branchgit branch -d branch-name
Stash changes before switchinggit 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.

Sharing Is Caring:

Leave a Comment