How to Move to Another Branch in Git: A Developer’s Guide

Branching is one of Git’s most powerful features. It allows developers to work on different parts of a project independently—such as features, bug fixes, or experiments—without interfering with the main codebase. If you’re learning Git or just need a refresher, understanding how to switch branches is essential.

In this post, we’ll walk through how to move to another branch in Git using the terminal.


What Is a Branch in Git?

A branch in Git is a lightweight, movable pointer to a specific commit. Think of it as a parallel version of your project where you can make changes, test features, and fix bugs without affecting the main or production branch.


Viewing Existing Branches

To see a list of all branches in your local repository, run:

git branch

This command shows:

  • A list of local branches
  • The branch you’re currently on, highlighted with an asterisk (*)

If you want to see remote branches as well, use:

git branch -a

Switching to an Existing Branch

To switch to another existing local branch, use:

git checkout branch-name

Or, using Git 2.23 and above (recommended):

git switch branch-name

Example:

git switch feature/login-page

✅ Tip: The switch command is more user-friendly and designed specifically for switching branches.


Creating and Switching to a New Branch

If the branch does not exist yet, you can create and switch to it in one step:

git checkout -b new-branch-name

Or using the newer command:

git switch -c new-branch-name

Example:

git switch -c feature/signup-flow

This creates a new branch based on your current branch and moves you into it.


Switching to a Remote Branch

If the branch exists on the remote (e.g., GitHub) but not locally, you can check it out like this:

git fetch origin
git checkout branch-name

Or:

git switch branch-name

Git will automatically create a local tracking branch linked to the remote.


Dealing with Uncommitted Changes

If you have changes that are not committed, Git might block the branch switch. You have a few options:

  1. Commit the changes:
git add .
git commit -m "WIP: ongoing changes"
  1. Stash the changes temporarily:
git stash
git switch branch-name

Later, you can retrieve them with:

git stash pop

Conclusion

Switching branches in Git is a core part of effective version control. Whether you’re reviewing code, fixing a bug, or developing a new feature, the ability to quickly move between branches ensures a clean, organized workflow.

Quick Summary:

  • git branch — List local branches
  • git switch branch-name — Switch to a branch (Git 2.23+)
  • git checkout branch-name — Switch to a branch (older syntax)
  • git switch -c new-branch — Create and switch
  • git stash — Save uncommitted changes temporarily

Mastering these simple commands will make you a more efficient and confident Git user.

Sharing Is Caring:

Leave a Comment