How to Switch Branches in Git Using Git Switch (With Examples)
How to Switch Branches in Git Using Git Switch (With Examples)
Gitis a robust version control system that allows developers to efficiently collaborate on projects, manage changes, and track different versions of their codebase. One of its standout features is branching, which enables developers to experiment, fix bugs, or develop features in isolated environments without disrupting the main codebase.
In this guide, we’ll learn how to use thegit switchcommand to change to a local and remote branch as well as switch back to the previous branch in Git. We’ll also discuss the differences betweengit switchandgit checkout, common errors, and best practices for usinggit switchefficiently.
Firstly, let’s understand what a branch is in Git and how it works.
What is a branch in Git?
A branch in Git is essentially a pointer to a specific snapshot of our project’s history. It allows us to diverge from the main line of development and keep working without affecting the main codebase. This makes branches an integral part of collaboration and experimentation in software development.
Imagine your project as a tree. The main trunk is yourmainormasterbranch, representing the stable version of your code. When you want to try a new feature, fix a bug, or work on a hotfix, you can create a new branch from the main one. This new branch lets you work in isolation while the main branch remains untouched.
Key characteristics:
- Lightweight:Branches in Git are not full copies of our project but rather references to commits, making them fast and efficient.
- Isolated:We can make changes on one branch without impacting others.
- Flexible:We can switch between branches, merge them, or delete them when they are no longer needed.
- Collaborative:Multiple team members can work on separate branches and merge their work later.
Now that we know how branches work in Git, let’s discuss how to switch to a local branch in Git usinggit switch.
Switch to a local branch in Git usinggit switch
Before we learn how to change branches usinggit switch, we need to have a local copy of the Git repository that we want to work on. For this tutorial, we’ll clone theCodecademy Docsremote repository to our local machine and work on it. Here, aremote repositoryrefers to a repository that’s hosted on a Git hosting platform, such asGitHub, GitLab, or Bitbucket.
So, let’s clone the repository to our local machine using thegit clonecommand:
git clone https://github.com/Codecademy/docs.git
Copy to clipboard
git clone https://github.com/Codecademy/docs.git
Then, navigate to the cloned remote repository:
cd docs
Copy to clipboard
cd docs
Now, we’re ready for thegit switchdemonstration.
To begin with, use thegit statuscommand to check the current branch in the cloned repository:
git status
Copy to clipboard
git status
Here is the output:
On branch mainYour branch is up to date with 'origin/main'.
nothing to commit, working tree clean
Copy to clipboard
On branch mainYour branch is up to date with 'origin/main'.
nothing to commit, working tree clean
As we can see here, we’re currently on themainbranch.
Now, let’s use thegit branchcommand to create another branch namedtest1:
git branch test1
Copy to clipboard
git branch test1
The syntax for switching branches is:
git switch branch-name
Copy to clipboard
git switch branch-name
Here,branch-nameis the name of the branch to which we intend to switch.
We will now use thegit switchcommand to change to the branchtest1from branchmain:
git switch test1Switched to branch ‘test1'
Copy to clipboard
git switch test1Switched to branch ‘test1'
We’ve now successfully switched to the branchtest1.
Moreover, we can create and switch to a local branch simultaneously using thegit switch -ccommand. This saves time when setting up new branches for features or experiments.
Here is the syntax for it:
git switch -c branch-name
Copy to clipboard
git switch -c branch-name
Let’s use thegit switch -ccommand to create and navigate to another branchtest2from branchtest1:
git switch -c test2Switched to a new branch 'test2'
Copy to clipboard
git switch -c test2Switched to a new branch 'test2'
As we can see, we’ve created and switched to a new branchtest2.
In the next section, we’ll learn how to use thegit switchcommand to change to a remote branch in Git.
Switch to a remote branch in Git usinggit switch
A remote branch exists on a remote repository, and we must fetch it to work with it locally. We can use thegit switchcommand to fetch and switch to a remote branch in the local repository.
For example, if we want to switch to thecppentryremote branch in the Codecademy Docs remote repository usinggit switch, we need to use this command:
git switch cppentry
Copy to clipboard
git switch cppentry
Switched to a new branch 'cppentry'branch 'cppentry' set up to track 'origin/cppentry'.
Copy to clipboard
Switched to a new branch 'cppentry'branch 'cppentry' set up to track 'origin/cppentry'.
We’ve now created and switched to a new branchcppentry, which is set up to track the fetchedcppentryremote branch fromorigin. Here,originis an alternative name for the Codecademy Docs remote repository, which was set automatically when we first entered the cloned remote repository on our local machine.
Moreover, the local branchcppentryis tracking the remote branchorigin/cppentry, which helps us pull and push changes from the local branch to the remote branch.
Alternatively, we can use thegit switch -ccommand to simultaneously create and switch to a branch while explicitly linking it to a remote branch. The linking enables us to pull and push changes from the local branch to the linked remote branch. Unlike thegit switchcommand, thegit switch -ccommand requires manually fetching the remote branches first.
So, let’s fetch the remote branches to make them available locally using this command:
git fetch
Copy to clipboard
git fetch
Then, list the fetched remote branches using thegit branch -rcommand:
git branch -rorigin/HEAD -> origin/mainorigin/agraves.test-branchorigin/cppentryorigin/dotnet...
Copy to clipboard
git branch -rorigin/HEAD -> origin/mainorigin/agraves.test-branchorigin/cppentryorigin/dotnet...
Next, change to the remote branchorigin/dotnetusing thegit switch -ccommand:
git switch -c dotnet origin/dotnetSwitched to a new branch 'dotnet'branch 'dotnet' set up to track 'origin/dotnet'.
Copy to clipboard
git switch -c dotnet origin/dotnetSwitched to a new branch 'dotnet'branch 'dotnet' set up to track 'origin/dotnet'.
As we can see,dotnetis the name of the new branch that gets created and switched to and then set up to track the remote branchorigin/dotnet.
Next, let’s understand how to switch back to the previous branch in Git usinggit switch.
Switch back to the previous branch in Git usinggit switch
We’ve seen how to switch to a local branch in Git using thegit switchcommand. The same syntax can be utilized to switch back to the previous branch in Git as well.
To begin with, let’s first switch to themainbranch:
git switch mainSwitched to branch ‘main’
Copy to clipboard
git switch mainSwitched to branch ‘main’
Then, let’s switch again to thetest1branch:
git switch test1Switched to branch ‘test1’
Copy to clipboard
git switch test1Switched to branch ‘test1’
Next, if we want to switch back to themainbranch, we can use the same command we used earlier:
git switch mainSwitched to branch ‘main’
Copy to clipboard
However, there is an alternative way to switch back to themainbranch. We can use thegit switch -command to switch back to the previous branch, i.e.,mainin this case. This command is particularly useful when alternating between two branches frequently, as it eliminates the need to remember branch names.
Primarily, let’s again switch to thetest1branch:
git switch test1Switched to branch ‘test1’
Copy to clipboard
Now, let’s use thegit switch -command to switch back to themainbranch for another time:
git switch -Switched to branch ‘main’
Copy to clipboard
git switch -Switched to branch ‘main’
We’re done learning how to usegit switchto change branches in Git. In the next section, let’s compare it to thegit checkoutcommand to understand how they differ in their functionalities.
Now that you’ve learned how to usegit switchto change branches, let’s comparegit switchwith the traditionalgit checkoutcommand.
Differences betweengit switchandgit checkout
Thegit switchcommand is a newer alternative to thegit checkoutcommand. Let’s check out the differences between them:
With the differences covered, let’s discuss some common errors that we may face while usinggit switch.
Common errors while usinggit switch
Understanding these commongit switcherrors and learning how to fix them will help us change branches in a smooth manner.
fatal: invalid reference: branch-name
Cause:The specified branch does not exist.
Solution:
Make sure you typed the branch name correctly. You can list available branches with:
git branch
Copy to clipboard
git branch
error: Your local changes to the following files would be overwritten by checkout
Cause:You have uncommitted changes that would be lost by switching branches.
You can run these commands to stash or keep the changes, switch to another branch, and then pop or import the changes:
git stashgit switch other-branchgit stash pop
Copy to clipboard
git stashgit switch other-branchgit stash pop
To discard the changes and switch to another branch:
git reset --hardgit switch other-branch
Copy to clipboard
git reset --hardgit switch other-branch
error: pathspec 'branch-name' did not match any file(s) known to git
Cause:The branch doesn’t exist, and you didn’t specify-cto create a new one.
If you’re trying to create a new branch:
git switch -c branch-name
Copy to clipboard
In the next section, we’ll discuss some best practices for usinggit switch.
Best practices for usinggit switch
Applying these best practices will help us switch branches efficiently:
- Use descriptive branch names: When using-cto create a branch, choose meaningful names that reflect the feature or fix, e.g.,git switch -c fix/login-bug.
- Avoid usinggit switchon detached HEADs: Be cautious when switching to commits directly (e.g.,git switch --detach <commit>), as it puts you in a detached HEAD state and changes won’t belong to a branch unless explicitly committed and assigned.
- Use-to quickly switch between branches:git switch -toggles between your current and last checked-out branch — useful when alternating between two branches frequently.
- Verify changes are committed or stashed before switching: Before switching branches, ensure you’ve committed or stashed changes to prevent merge conflicts or lost work.
Conclusion
In this tutorial, we discussed how to switch a branch in Git using thegit switchcommand. We learned how to clone a remote repository, create a branch, switch to a local and remote branch and switch back to the previous branch. By mastering thegit switchcommand, we can seamlessly navigate between branches and manage our codebase more efficiently.
If you want to learn more about Git branching and collaboration, check out theLearn Git: Branching and Collaborationcourse on Codecademy.
Frequently Asked Questions
1. What happens to my current changes when I usegit switch?
If you have uncommitted changes that conflict with the target branch, Git will prevent you from performinggit switch. You must either commit, stash, or discard the changes first.
2. Isgit switchavailable in all Git versions?
No,git switchwas added in Git 2.23. Older versions requiregit checkout.
3. How do I switch to a branch with the same name as a remote branch?
Usegit switch -c <branch-name> --track origin/<branch-name>to create a local branch that tracks or points to the remote one.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Complete Payment to Unlock Full Guide & Source Code
You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.
Ready to access the complete step-by-step tutorial?
Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.
How to Squash Commits in Git (Step-by-Step with Examples)
Next BlueprintHow to Take This Course
Related Project Guides
View all 412 →Android Studio Quick-Start Guide
Android Studio often intimidates beginners, but by learning a few handy shortcuts and getting the lay of the land, we can navigate this powerful development environment with ease.
Developer toolsApache Kafka Tutorial: A Complete Guide for Beginners
Apache Kafkais a well-known distributed event streaming platform designed to efficiently manage real-time data feeds. It was originally developed by LinkedIn in 2011 and later open-sourced. Apache Kafka has gained immens...
Developer toolsBuilding Websites with Wix
Creating a website has never been easier. Previously, making a presentable website meant learning HTML, CSS, andJavaScript. The whole process could take weeks, months, or even years before creating a website that you’re...
Ready to start building your next project?
Enjoyed this guide? Continue exploring our library of 412+ step-by-step guides, starter files, and practical projects across Web Development, Mobile Apps, AI, and Design.