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.