Navigating between different lines of development is an everyday task. For over 14 years, developers used git checkout for this. But because checkout was overloaded with multiple conflicting duties, Git introduced git switch in 2019 to provide a safer, cleaner branch navigation experience.
git switch Command# Switch to an existing branch:
$ git switch feature/auth
# Create a brand-new branch AND switch to it in one command:
$ git switch -c feature/payments
# (-c stands for create)
# Switch back to the previous branch you were just working on:
$ git switch -
git switch with Legacy git checkout| Operation Task | Modern Command (Git 2.23+) | Legacy Command |
|---|---|---|
| Switch to existing branch | git switch branch-name |
git checkout branch-name |
| Create and switch to new branch | git switch -c new-branch |
git checkout -b new-branch |
| Switch back to previous branch | git switch - |
git checkout - |
| Discard file changes (files only) | git restore filename |
git checkout -- filename |
Normally, the HEAD pointer points to a branch name (like main), and that branch points to the latest commit. When you commit, the branch automatically advances with you.
A Detached HEAD state occurs when you checkout a specific historical commit hash, a remote branch, or a tag directly instead of a local branch name:
$ git checkout 8a2f1b4
Note: switching to '8a2f1b4'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them...
In detached HEAD state, HEAD points directly to the commit object, not a branch. If you make new commits here and then switch back to main, those new commits will be orphaned and eventually cleaned up by Git's garbage collection!
If you made commits in detached HEAD state and want to keep them, simply create a new branch at your current position before leaving:
$ git switch -c my-recovered-experiments
If you were just inspecting old code and want to return safely without keeping changes:
$ git switch main
Strengthen your version control mastery by studying these connected classes:
Create, rename, list, and delete local and remote branches in Git.
The companion command to git switch that handles file-level restoration.
Safely stash dirty working changes before hopping between disparate branches.
Understand how the .git/HEAD file points to symbolic branch references.
Advance your software engineering skills with the next topic in our synchronized curriculum.
Continue to Merge Strategies → Previous: ← Branching Basics | Full Syllabus