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:
- Commit the changes on the current branch first, then switch.
- Stash them with
git stash, switch, and latergit stash popto bring them back. - 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.