Git and GitHub Basics
Branches and Merging
In this lesson you will
- Explain what a branch is and why it is useful
- Create, switch and merge branches
- Understand what a merge conflict is
Introduction
Imagine you want to try a new design, but your site must keep working in the meantime. A branch is a separate line of work. You can experiment on it, and the main line stays untouched until you decide to combine them.
The simple explanation
A branch is a safe copy of your project's history where you can work without affecting the main version.
Your main line is usually called main. A branch is cheap in Git, so developers make one for almost every feature or fix.
Create and switch
Terminal
# create a branch and move onto it
git switch -c add-footer
# check where you are
git branchgit branch lists your branches and marks the one you are on with a star. Now make changes and commit as normal. Those commits belong to add-footer only.
To return to the main line:
Terminal
git switch mainNotice that the files change back to how they were on main. Your work on the other branch is still safe.
Merge your work back
When the feature is finished, go to the branch you want to update (usually main) and merge:
Terminal
git switch main
git merge add-footerGit combines the histories. Often this works automatically.
Quick quiz
Why do developers use branches?
Merge conflicts
If two branches changed the same lines of the same file, Git cannot decide which to keep. It stops and marks the file with a conflict. This is normal, not a disaster:
- Open the marked file. Git shows both versions between markers of
<<<<<<<,=======and>>>>>>>. - Edit the file to the final text you want and delete the marker lines.
- Run
git addon the file, thengit committo finish the merge.
If you get lost, git merge --abort returns you to before the merge.
Try it yourself
Create a branch, commit a change on it, switch back to main and confirm the change is not there. Then merge the branch and check that it appears.
Summary
- A branch is a separate line of work that keeps
mainsafe. - Use
git switch -c nameto create,git switch nameto move, andgit merge nameto combine. - A conflict means two changes touched the same lines. Fix the file, add it and commit.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading