Course contents

Switch to an existing branch

Sign in to run this lab and save your progress

Learn

You've made a branch. Now you want to actually work on it. Switching to a branch tells Git: "the commit this branch points at is now my working state, and future commits I make should extend this branch."

The command

git switch feature

That's it. HEAD (Git's name for "the current position") moves onto the feature branch. From now on, every commit you make advances feature and leaves main where it was.

You'll also see the older command git checkout feature in tutorials and code samples. It does the same thing for this purpose. git switch was introduced in Git 2.23 specifically to be a clearer, safer command for changing branches. Use switch when you have the choice, and don't be surprised when you see checkout in older material.

What happens to your files

If the two branches point at the same commit (as they do right after git branch feature), nothing on disk changes. You're looking at the same snapshot. Only the label attached to your position moves.

But if the branches have diverged, if feature has commits main doesn't or vice versa, switching physically rewrites the files in your working directory to match the new branch's snapshot. Files unique to one branch appear or disappear. Modified files change to match the target branch's version.

This is one of the most surprising things Git does the first time you see it. Your text editor will suddenly show different contents. Nothing is lost, the other branch's snapshot is safe in Git's storage. But it can feel like magic (or a bug). It isn't. It's just Git updating disk to match the branch you asked for.

Uncommitted changes block a switch

If you have uncommitted changes and try to switch to a branch that would overwrite those changes, Git refuses:

error: Your local changes to the following files would be
overwritten by checkout: ...
Please commit your changes or stash them before you switch branches.

This is Git protecting your work. Your options:

  1. Commit the changes on the current branch first, then switch.
  2. Stash them with git stash, switch, and later git stash pop to bring them back.
  3. Discard them if they don't matter (careful; use git restore .).

Git will never overwrite your changes without asking. If a switch "just works", it's because there was no conflict to resolve.

Create and switch in one step

Once you've done a few branch operations, you'll notice you almost always create a branch AND switch to it. Git has a shortcut:

git switch -c feature

Equivalent to git branch feature && git switch feature. Same mental model, one less command to type.

Your task

This repository has two branches: main (where you are now) and feature. Both currently point at the same commit. Switch to feature so that HEAD moves to it. After this, git status should report On branch feature.