← Back to Git Course | Chapter 3: Branching | Lesson 4 of 9

Git switch Command

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

bash
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

bash
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

bash
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

bash
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

bash
git switch main
# error: Your local changes would be overwritten
git stash
git switch main

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.