Create and switch branches

safe beginner #branch#switch#new branch

When to use this: You want to try a change without touching main, or jump between pieces of work.

Before you start

Steps

  1. Create a branch and switch to it

    terminal
    git switch -c feature-hero

    -c creates the branch from where you are now and moves you onto it. Pick a short descriptive name with no spaces.

  2. Work and commit as usual

    terminal
    git add -A
    git commit -m "Add hero section"

    Commits land on feature-hero. main is untouched.

  3. Publish the branch to GitHub

    terminal
    git push -u origin feature-hero

    First push of a branch needs -u. Vercel creates a preview deployment for it.

  4. Switch between branches

    terminal
    git switch main
    git switch feature-hero

    Your files change to match the branch you switch to.

  5. List branches and what they track

    terminal
    git 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-current prints the branch you expect.

How to undo it

Created by mistake and nothing committed yet? Go back and delete it:

terminal
git switch main
git branch -d feature-hero

Common 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.

Practice these as flashcards →

Terms in this scenario

Related scenarios

My notes

Saved in this browser only.