git switch
Switch branches
The 'git switch' command moves you to another branch: HEAD follows it and your working files change to match that branch. With -c it creates the branch first. It was added in Git 2.23 to take over the branch-switching half of git checkout, with clearer names and safer defaults — it refuses to switch when that would overwrite your uncommitted edits.
Synopsis
git switch [<options>] <branch>
git switch [<options>] (-c|-C) <new-branch> [<start-point>]
git switch [<options>] --detach [<start-point>]
git switch [<options>] --orphan <new-branch>Options
Choosing the Right Option
switch vs checkout
The same branch actions, old and new
| Command | git checkout equivalent |
|---|---|
git switch main | git checkout main |
git switch -c feature/login | git checkout -b feature/login |
git switch --detach HEAD~1 | git checkout HEAD~1 |
git switch - | git checkout - |
Examples
Switch to a branch
git switch mainMove to main.
Create and switch
git switch -c feature/loginCreate feature/login and move to it.
Previous branch
git switch -Go back to the branch you were on before.
Track a remote branch
git switch feature/loginIf only origin/feature/login exists, a local branch tracking it is created.
Workflow Examples
git switch mainStart from main
git pullGet the latest main
git switch -c feature/loginCreate your branch
git stashPark the edits
git switch mainSwitch
git switch - && git stash popCome back and restore the edits
Troubleshooting
error: Your local changes to the following files would be overwritten by checkout
Cause: An uncommitted edit conflicts with the other branch
Commit or stash it first, or use --discard-changes to throw it away
fatal: invalid reference: feature/x
Cause: The branch does not exist
Create it with git switch -c, or run git fetch if it exists on origin
fatal: a branch is expected, got commit
Cause: You gave a commit, not a branch
Use git switch --detach <commit>
Tips & Pitfalls
Best Practices
- ✓Use git switch for branches and git restore for files instead of git checkout.
- ✓Keep a clean status (commit or stash) before switching.
- ✓Pull main before creating a new branch from it.
Common Mistakes
- ✗Switching with uncommitted edits and being surprised they follow you to the new branch.
- ✗Using git switch <commit> — commits need --detach.
- ✗Forgetting -c and getting "invalid reference" for a branch that does not exist yet.
FAQ
For branches it does the same job, but with clearer options and it cannot touch files by accident.
Git 2.23 or newer.
They follow you to the new branch, unless they conflict — then the switch is refused.