Switching Between Branches
Learn about Switching Between Branches
Switching between branches changes the files in your working directory to match the branch you're moving to. Git does this instantly — swapping out file contents to match the snapshot of that branch. This episode covers switching branches safely and handling common edge cases.
Switching Branches
# Switch to an existing branch
git checkout main
git checkout feature/login
# Newer syntax (recommended)
git switch main
git switch feature/login
# Switch and create in one step
git checkout -b new-feature
git switch -c new-feature
What Happens When You Switch
When you switch from feature/login to main, Git:
- Updates your working directory files to match
main - Updates the staging area to match
main - Moves the
HEADpointer tomain
Files that exist only on feature/login disappear (don't worry, they're still stored in Git). Files that were modified on main show up with those changes. It's like teleporting between parallel universes.
Switching with Uncommitted Changes
Git won't let you switch branches if you have uncommitted changes that would conflict with the destination branch:
git switch main
# error: Your local changes to the following files would be overwritten by checkout:
# src/app.js
# Please commit your changes or stash them before you switch branches.
You have three options:
Option 1: Commit Your Changes
git add .
git commit -m "WIP: login validation"
git switch main
Option 2: Stash Your Changes
# Save changes temporarily
git stash push -m "WIP login work"
# Switch branches
git switch main
# Later, come back and restore
git switch feature/login
git stash pop
Option 3: Discard Your Changes
# Only if you don't need the changes
git restore .
git switch main
Detached HEAD State
If you checkout a specific commit (not a branch), you enter a "detached HEAD" state:
git checkout a1b2c3d
# You are in 'detached HEAD' state...
This means you're not on any branch. You can look around and make experimental changes, but if you want to keep them, create a branch:
# Create a branch from detached HEAD
git switch -c experiment/from-old-commit
# Or go back to an existing branch
git switch main
Stashing in Detail
# Stash current changes
git stash
# Stash with a message
git stash push -m "WIP: user profile page"
# List all stashes
git stash list
# Apply the latest stash (keep it in stash list)
git stash apply
# Apply and remove from stash list
git stash pop
# Apply a specific stash
git stash apply stash@{1}
# Drop a stash
git stash drop stash@{0}
# Clear all stashes
git stash clear
What's Next
You can now confidently switch between branches. In the next episode, we'll learn the art of merging — combining work from different branches back together.