Create and switch branches
When to use this: You want to try a change without touching main, or jump between pieces of work.
Before you start
Steps
-
Create a branch and switch to it
terminalgit switch -c feature-hero-ccreates the branch from where you are now and moves you onto it. Pick a short descriptive name with no spaces. -
Work and commit as usual
terminalgit add -A git commit -m "Add hero section"Commits land on
feature-hero.mainis untouched. -
Publish the branch to GitHub
terminalgit push -u origin feature-heroFirst push of a branch needs
-u. Vercel creates a preview deployment for it. -
Switch between branches
terminalgit switch main git switch feature-heroYour files change to match the branch you switch to.
-
List branches and what they track
terminalgit branch -vv*marks the current branch. Brackets show the upstream, e.g.[origin/feature-hero: ahead 1].
How to verify it worked
git branch --show-currentprints the branch you expect.
How to undo it
Created by mistake and nothing committed yet? Go back and delete it:
git switch main
git branch -d feature-heroCommon errors and fixes
invalid reference: <name> when switching The branch does not exist locally. Check the spelling with git branch -a, or create it with -c. If it exists on GitHub, git fetch first. Your local changes would be overwritten by checkout Commit or stash first. Q&A
What is the difference between git switch and git checkout?
switch only changes branches and restore only restores files. checkout does both, which is confusing, so the newer commands are clearer.
Does a branch copy my files?
No. A branch is just a label on a commit, so creating one is instant and free.