git switch
Description:
Switch between branches. Introduced in Git 2.23 as a clearer alternative to git checkout for branch switching.
Syntax:
bash
git switch <branch-name>
git switch -c <new-branch>
git switch -Examples:
bash
# Switch to existing branch
git switch develop
# Create and switch to new branch
git switch -c feature/authentication
# Create branch from specific starting point
git switch -c hotfix/bug origin/main
# Switch to previous branch
git switch -
# Switch to remote branch (creates local tracking branch)
git switch feature/api-integrationDetailed Explanation:
- Branch-focused: Unlike
git checkout, this command only switches branches (more focused purpose) - Clearer intent: Makes code more readable and reduces confusion about what the command does
- Automatic tracking: When switching to a remote branch, automatically creates a local tracking branch
- Safer: Less chance of accidentally modifying files or entering detached HEAD state
Common Errors:
fatal: invalid reference: <branch>→ Solution: Branch doesn't exist; usegit switch -cto create iterror: Your local changes would be overwritten→ Solution: Commit, stash, or discard changes firstfatal: a branch is expected, got commit→ Solution: Usegit checkoutfor commits;git switchis for branches only
Pro Tips:
- Prefer
git switchovergit checkoutfor branch operations (clearer and safer) - Use
--discard-changesto force switch even with uncommitted changes:git switch --discard-changes main - Quick branch creation:
git switch -cis shorter thangit checkout -b - Use tab completion to avoid typos in branch names
- Combine with
git branch -ato see available branches before switching
Related Commands:
git checkout– Legacy command with multiple purposesgit branch– List or create branchesgit restore– Restore files (separate from branch switching)git merge– Combine branches after switching