How to Switch Branches in Git: A Beginner-Friendly Guide

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 or master β†’ the production-ready branch
  • feature/login β†’ a new feature branch
  • bugfix/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

TaskCommand
List all branchesgit branch
Switch to a branch (modern)git switch branch-name
Switch to a branch (legacy)git checkout branch-name
Create and switch to new branchgit switch -c new-branch
Save changes before switchinggit 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.

Sharing Is Caring:

Leave a Comment