Lesson 3 of 8
Branches
Learn to create, switch between and merge branches. A branch lets you work on a change separately; if it works you merge it into main, and if not you delete it.
The default branch is usually called main. Creating a branch is instant and free — just writes a 43- file pointing at a commit. The universal workflow: never work directly on main; make a branch per feature or fix, merge it when done.
git branch # list branches (* = current)
git switch -c add-login # create branch and switch to it
# ...edit files, add, commit as usual...
git add .
git commit -m "Add login page"
git switch main # back to main
# Your login changes 'disappear' — they live on the branch.
git switch add-login # and they're back# Merge the branch into main:
git switch main
git merge add-login
# Fast-forward or merge commit — either way, main now has the work.
git branch -d add-login # delete the merged branch
# See the shape of history:
git log --oneline --graph --allCommon question
Is a branch a copy of the project?
Git stores commits as a graph that never changes. A branch is a name pointing at one commit, and it moves forward as you commit. Because the graph is shared, ten branches cost almost nothing, and switching between them only changes which snapshot your working directory shows.
Work like this: make a branch for each piece of work, commit freely on it, then merge it into main when it is done and tested. Delete the branch afterwards; its commits live on in main. Keep main in a state you could deploy at any moment, and keep everything unfinished on branches.
Source: The Git documentation calls a branch "a lightweight movable to a commit".
Common mix-ups
Each of these sounds reasonable. Think about why it is wrong, then open the explanation.
Switching branches must copy the files, since the working directory changes.
Branches are for big features, so small fixes should go straight to main.
Merging rewrites history, so the branch's commits disappear.
Tip: use the ← and → keys to move between lessons.