git switch — Modern Branch Switching
How to switch branches cleanly in modern Git: creating and switching (-c), switching to existing branches, and why switch replaces checkout.
git switch — Modern Branch Switching
Introduced in Git 2.23, git switch is the dedicated, modern command designed specifically for switching and creating branches, replacing the overloaded legacy git checkout command.
1. Syntax and Basic Usage
# 1. Switch to an existing local branch:
git switch main
# 2. Create a new branch and switch to it immediately (-c):
git switch -c feat/dark-mode
# 3. Switch to a remote tracking branch from GitHub:
git switch feature-from-colleague
# 4. Switch back to the previous branch you were just on (-):
git switch -2. Why git switch Replaced git checkout
Historically, git checkout was used for two completely unrelated tasks:
- Switching branches (
git checkout main) - Overwriting/discarding uncommitted file changes (
git checkout -- file.txt)
This ambiguity caused developers to accidentally discard uncommitted work. Modern Git separated these responsibilities:
git switch: Exclusively switches and creates branches.git restore: Exclusively discards and restores files.
Related Topics
Git Branches & Branching Strategies
Understanding Git branches: lightweight movable pointers, branch creation, listing, deleting, trunk-based development, and GitHub flow.
git checkout — Legacy Branch & Commit Inspection
Understanding legacy git checkout: checking out commits (detached HEAD state), legacy branch switching (-b), and modern replacements.