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

Git switch Command

git switch is the simpler way to walk between rooms of your project. It was made because the old checkout command did too many different jobs.
Syntax
bash
git switch branch_name
git switch -c new_branch_name
git switch -

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using git switch file.txt to restore a file, when switch only changes branches; use git restore.
  2. Running git switch new-branch for a branch that does not exist, when creating one needs -c.
  3. Following older tutorials on a Git version before 2.23, where git switch is not available.

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.