Creating branches is only half the battle; navigating between them is an everyday developer reflex. Over Git's history, the command for switching branches has evolved to be safer and more intuitive.
1. The Modern Command: git switch
Historically, the git checkout command was used for both switching branches AND discarding file changes. Because this dual role caused confusion and accidental data loss, Git 2.23 introduced two dedicated commands:
git switch: Exclusively for switching and creating branches.
git restore: Exclusively for discarding or un-staging file changes.
Switching Between Existing Branches:
1# Switch to an existing local branch named 'dev'
2git switch dev
Terminal output:
1Switched to branch 'dev'
2Your branch is up to date with 'origin/dev'.
Creating and Switching in One Step (-c flag):
To create a brand new branch and immediately switch HEAD to it:
1git switch -c feature-user-profile
Terminal output:
1Switched to a new branch 'feature-user-profile'
Switch Back to the Previous Branch (-):
Just like cd - in terminal shells, you can instantly hop back to whatever branch you were on previously:
1git switch -
2. The Traditional Command: git checkout
Because millions of tutorials, StackOverflow answers, and CI/CD pipelines use git checkout, every developer must know its syntax:
1# Switch to an existing branch
2git checkout main
3
4# Create and immediately switch to a new branch (-b flag)
5git checkout -b feature-dark-mode
Note
[!NOTE]
git switch -c <name> is modern, clearer, and equivalent to git checkout -b <name>. Both commands accomplish the exact same outcome under the hood.
3. What Happens in Your Working Directory When You Switch?
When you run git switch <branch>:
1
Git moves HEAD to point to the new branch pointer.
2
Git rewrites the files in your Working Directory to match the snapshot of the commit pointed to by that branch!
3
Files created in the other branch disappear from your disk, and files present in the target branch materialize instantly.