Switching Branches
13.1 Switching to an Existing Branch
The modern recommended command:
Example:
Older (still supported):
Both do the same:
✔ Updates your working directory
✔ Points HEAD to the target branch
1git switch <branch-name>Example:
1git switch feature/login-authOlder (still supported):
1git checkout <branch-name>Both do the same:
✔ Updates your working directory
✔ Points HEAD to the target branch
13.2 Auto-Stash Behavior (Newer Git Versions)
If you have uncommitted changes and you try switching branches, Git may refuse.
You have options:
Option 1 — Commit your work
Option 2 — Stash changes and switch
Option 3 — Use auto-stashor
Use with caution — this can overwrite your work.
You have options:
Option 1 — Commit your work
1git add .
2git commit -m "WIP: partial work"Option 2 — Stash changes and switch
1git stash
2git switch mainOption 3 — Use auto-stash
1git switch <branch-name> --discard-changes1git switch <branch-name> --mergeUse with caution — this can overwrite your work.
13.3 Switching Back to the Previous Branch
A super useful shortcut:
Example:
This toggles between the last two branches, like a back/forward button.
1git switch -Example:
1git switch main
2git switch feature/cart-ui
3git switch -This toggles between the last two branches, like a back/forward button.
13.4 Viewing Which Branch You Are On
1git branchThe active branch will be highlighted with:
1* feature/login-auth
2 main
3 devYou are always on the branch marked with *.
13.5 Switching to Remote Branches
To move to a branch that exists on the remote but not locally:
Example:
This creates a local copy tracking the remote branch.
1git switch -c <branch-name> origin/<branch-name>Example:
1git switch -c design-update origin/design-updateThis creates a local copy tracking the remote branch.
13.6 Detached HEAD State
If you switch to a commit instead of a branch:
or using older syntax:
You enter detached HEAD, meaning:
• You are not on a branch
• New commits do not belong to any branch
• They can be lost if not saved
To save the work:
1git switch --detach <commit-hash>or using older syntax:
1git checkout <commit-hash>You enter detached HEAD, meaning:
• You are not on a branch
• New commits do not belong to any branch
• They can be lost if not saved
To save the work:
1git switch -c new-branch-name13.7 Key Takeaways
• Use git switch <branch> for modern switching; git checkout still works.
• Switch safely: stash or commit before changing branches to prevent data loss.
• git switch - toggles between the last two branches.
• Remote branches require git switch -c <branch> origin/<branch>.
• Switching to a commit creates a detached HEAD, so create a branch if you want to keep the work.
• Switch safely: stash or commit before changing branches to prevent data loss.
• git switch - toggles between the last two branches.
• Remote branches require git switch -c <branch> origin/<branch>.
• Switching to a commit creates a detached HEAD, so create a branch if you want to keep the work.