Git switch Command
In this page:
Basic Switching with git switch
git switch was added in Git 2.23 specifically to replace the branch-switching half of the older, overloaded git checkout command, giving branch changes a dedicated, less error-prone command with a narrower, clearer purpose.
Example: Basic Switching with git switch
git switch main
Creating and Switching with -c
git switch -c <new-branch> creates a new branch and moves onto it in one step -- functionally the same outcome as git checkout -b, just under the newer, more explicit command name.
Example: Creating and Switching with -c
git switch -c feature-cart
Switching Back and Tracking
git switch - jumps back to whichever branch you were on before your last switch, a quick shortcut for bouncing between two branches; git switch <remote-branch> sets up local tracking of a remote branch directly.
Example: Switching Back and Tracking
git switch -
git switch origin-feature
Detached HEAD with --detach
Unlike git checkout, which quietly enters detached HEAD when given a commit hash, git switch requires the explicit --detach flag to do the same thing -- a deliberate design choice to prevent accidentally losing track of your branch.
Example: Detached HEAD with --detach
git switch --detach a1b2c3d
Handling Conflicting Local Changes
If your uncommitted changes would be overwritten by the branch you're trying to switch to, git switch refuses and shows an error rather than silently discarding or merging them -- you must first commit, stash, or force the switch to proceed.
Example: Handling Conflicting Local Changes
git switch main
# error: Your local changes would be overwritten
git stash
git switch main
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: