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:
| Command | What it does |
|---|---|
git checkout feature | Switch to a branch |
git checkout -- file.txt | Restore a file (discard changes) |
git checkout abc1234 | Detach HEAD at a commit |
This can be confusing and even dangerous. git switch and git restore split these responsibilities:
git switch— only for switching branchesgit restore— only for restoring files
Try it!
Practice using git switch for branch operations:
- Create a file and commit:
echo "start" > app.txtthengit add app.txtthengit commit -m "Initial commit" - Create and switch to a new branch:
git switch -c feature - Verify you are on the new branch:
git branch - Make a commit:
echo "feature work" >> app.txtthengit add app.txtthengit commit -m "Add feature work" - Switch back to main:
git switch main - Toggle back to feature:
git switch - - Switch to main again:
git switch main - Create a branch from a specific point:
git switch -c hotfix feature - Check the log:
git log --oneline— you should see the feature commit becausehotfixstarted fromfeature
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.