git branch & git switch

Work on a branch

Lesson 9 of 20 · 9 min · Module 3: Branches

Want to try an idea without risking the working version? Put it on a branch. Branches let you work on several things at once and keep main safe.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Explain what a branch is
  • Create and switch branches
  • See how switching changes your files

The idea

A branch is a movable label that points at a commit; main is the one Git made for you. git switch -c name creates a branch and switches to it. New commits move the current branch forward while the others stay where they are. git switch main takes you back, and Git changes the files in your folder to match. git branch lists branches and marks the current one with *.

git switch -c dark-mode
git commit -am "Add dark mode colours"
git switch main
git branch

01A branch is a label on a commit

A branch is a name that points at a commit. Look inside .git: HEAD says which branch you are on, and the branch itself is a tiny file holding a commit hash.

cat .git/HEAD
cat .git/refs/heads/main
Output
ref: refs/heads/main
4abfd2a8731b11abeeea1e60e8d482088106f3f5

02Create and switch in one go

git switch -c name creates a branch at the current commit and switches to it. git branch lists the branches and marks the current one with *.

git switch -c dark-mode
git branch
Output
Switched to a new branch 'dark-mode'
* dark-mode
  main

03Switching changes your files

When you switch, Git updates the files in your folder to match the commit the branch points to. Work committed on another branch disappears from view and comes back when you switch back.

Your turn

Create a branch called dark-mode and switch to it. Add the line body { background: #111; color: #eee; } to the end of style.css and commit it as Add dark mode colours. Switch back to main, show style.css there with cat, and list your branches with git branch.

What the checks look for

  • The dark-mode branch has your commit
  • main does not have it
  • You finish on main, where style.css has no dark colours
  • Lists the branches
Try it in the editor →

Take this with you

Branches let you try ideas without touching main; git switch moves between them.

Go a little further

Run git log --oneline --all --graph to see both branches. Older tutorials use git checkout -b instead of git switch -c; both work.

Learn Git & GitHub for free

20 short lessons with real code and instant checks.

See the whole course →