Branches and Merging
You are halfway through a wishlist feature when checkout breaks in production. You need to fix checkout now, without shipping your half-built wishlist. Branches let two lines of work live side by side and join up only when each is ready.
The rule
A branch is just a name that moves forward with your commits.
A branch is not a copy of your files. It is a small label pointing at one commit. When you commit on a branch, the label moves to the new commit. HEAD is Git's marker for "the branch you are on right now".
git switch -c wishlist # create a branch here and move onto it
# ...edit, add, commit...
git switch main # go back; your files change to main's version
git merge wishlist # bring wishlist's commits into main
git branch -d wishlist # delete the label once merged(Older guides use git checkout -b wishlist; it does the same thing.) git branch lists your branches and marks the current one with *, and git log --oneline --graph --all draws the lines of commits so you can see where they fork.
When you merge, Git combines the two histories:
- If
mainhas not moved since you branched, Git simply slides themainlabel forward. This is a fast-forward. - If both branches have new commits, Git creates a merge commit with two parents that joins them.
If both sides changed the same lines of the same file, Git cannot decide which version wins. It stops with a merge conflict and marks the spot:
<<<<<<< HEAD
MAX_QUANTITY = 10
=======
MAX_QUANTITY = 20
>>>>>>> wishlistYou edit the file to the correct final version, remove the markers, then git add the file and git commit to finish the merge.
The shortcut
Keep main always working, and one branch per change. Before merging, picture the two lines of commits: a straight line means fast-forward, a fork means a merge commit, and overlapping edits to the same lines mean a conflict.
Branch for the feature
On
main, rungit switch -c wishlistand commit your work there.
The trap is one long-lived branch collecting weeks of changes. The longer two branches drift apart, the bigger and more painful the conflicts. Merge small branches often.
Drills
Answer fast — trust the rule.
What is a Git branch, underneath?
You branch from main, make 3 commits, and nobody changes main. What does merging into main do?
When does a merge conflict happen?
You have fixed the conflicting lines and removed the markers. What finishes the merge?
Remember
- A branch is just a name that moves forward with your commits.
- One branch per change; straight line → fast-forward, fork → merge commit, same lines → conflict.
- Merge small branches often so conflicts stay small.
