W3docs

git switch

Learn the git switch command — the modern, purpose-built way to change and create branches. See how it differs from git checkout, with examples.

Definition

The git switch command changes the branch you are working on. Introduced in Git 2.23, it was carved out of the overloaded git checkout command to do one job clearly: move HEAD to another branch and update your working tree to match. Anything to do with restoring files now lives in git restore, so switch stays focused on branches alone.

git switch moving HEAD from one branch to another

Why git switch exists

For years, git checkout handled two unrelated tasks: switching branches and restoring files in the working tree. That overloading made it easy to lose work by accident — git checkout <file> silently discarded changes, while git checkout <branch> moved you somewhere new. Git 2.23 split the responsibilities so that each command is predictable. git switch is still marked experimental in the documentation, but it is stable and recommended for everyday use.

Switching to an existing branch

To move onto a branch that already exists, name it:

git switch feature

HEAD now points at feature, and your working directory reflects that branch's latest commit. If you have uncommitted changes that would be overwritten, Git stops and warns you rather than throwing the work away.

Creating and switching in one step

Use the -c (create) flag to make a new branch and move onto it immediately:

git switch -c new-feature

This is the modern equivalent of git checkout -b new-feature. You can also base the new branch on a specific starting point:

git switch -c hotfix main

Common options

CommandDescription
git switch <branch>Switches to an existing branch.
git switch -c <branch>Creates a new branch and switches to it.
git switch -c <branch> <start-point>Creates a branch from a given commit or branch and switches to it.
git switch -Switches back to the previously checked-out branch.
git switch --detach <commit>Checks out a commit directly in a detached HEAD state.
git switch -C <branch>Creates the branch, or resets it if it already exists, then switches.

Going back to where you were

A single dash returns you to the branch you were on before:

git switch -

This is handy when you are bouncing between two branches and do not want to type their names repeatedly.

git switch vs git checkout

Both commands can change branches, so why prefer switch? Because it cannot touch your files by accident. git checkout accepts both branch names and file paths, which means a typo can quietly overwrite your work. git switch only ever deals with branches; if you want to discard changes to a file, you reach for the clearly named git restore instead.

# Old, overloaded way
git checkout main
git checkout -b feature

# Modern, explicit way
git switch main
git switch -c feature

Practice

Practice

Which statements about 'git switch' are correct?