Tour of Git
Branching & Merging / Lesson 2.9

git switch — The Modern Way to Switch Branches

Git 2.23 introduced git switch as a cleaner alternative to git checkout for switching branches. While checkout does many things (switch branches, restore files, detach HEAD), switch does one thing: switch branches.

Switching Branches

git switch feature

This is equivalent to git checkout feature, but the intent is clearer.

Creating and Switching in One Step

git switch -c new-feature

The -c flag creates the branch and switches to it. This replaces git checkout -b.

Switching Back to the Previous Branch

git switch -

The dash means "the branch I was on before" — handy for toggling between two branches.

Creating a Branch from a Specific Starting Point

git switch -c bugfix main

This creates bugfix starting from the tip of main, regardless of which branch you are currently on.

Why Use switch Instead of checkout?

git checkout is overloaded — it does too many different things:

CommandWhat it does
git checkout featureSwitch to a branch
git checkout -- file.txtRestore a file (discard changes)
git checkout abc1234Detach HEAD at a commit

This can be confusing and even dangerous. git switch and git restore split these responsibilities:

  • git switch — only for switching branches
  • git restore — only for restoring files

Try it!

Practice using git switch for branch operations:

  1. Create a file and commit: echo "start" > app.txt then git add app.txt then git commit -m "Initial commit"
  2. Create and switch to a new branch: git switch -c feature
  3. Verify you are on the new branch: git branch
  4. Make a commit: echo "feature work" >> app.txt then git add app.txt then git commit -m "Add feature work"
  5. Switch back to main: git switch main
  6. Toggle back to feature: git switch -
  7. Switch to main again: git switch main
  8. Create a branch from a specific point: git switch -c hotfix feature
  9. Check the log: git log --oneline — you should see the feature commit because hotfix started from feature

Key Insight

git switch and git checkout do the same job for switching branches. If you are learning Git fresh, prefer git switch — it is simpler and safer. If you already use checkout out of habit, that is fine too. Both will be supported for the foreseeable future.

🎯

Goal

Use git switch to create and switch between branches

Terminal
$

No commits yet. Run `git init` and create your first commit.