Git by Example: Branch Switching
Learn how to navigate between different branches in your repository. This example compares the classic git checkout command with the modern git switch command.
Code
# Switch to an existing branch (old way)
git checkout main
# Switch to an existing branch (new way)
git switch feature-login
# Output:
# Switched to branch 'feature-login'
# Switch to the previous branch (like TV remote)
git switch -
# Output:
# Switched to branch 'main'
# List all branches to see where you are
git branch -aExplanation
Switching branches updates the files in your working directory to match the version stored in the target branch. It also moves the HEAD pointer to point to the new branch. This allows you to context switch between different tasks, like pausing work on a feature to fix a critical bug on the main branch.
For years, git checkout was the only command for this, but it was also used for restoring files, which confused many users. The git switch command was introduced to do exactly one thing: switch branches. It is safer and easier to understand for beginners.
A handy trick is using git switch - (or git checkout -), which toggles you back to the last branch you were on. This is incredibly useful when you need to quickly check something on another branch and return.
- Updates working directory files to match the branch
- Moves the HEAD pointer
git switchis preferred overgit checkout- Use
-to toggle to the previous branch

