Branching & Merging in Git
Version control isn’t just about tracking code — it’s about working smarter. One of Git’s most powerful features is branching.
What is a Branch?
Imagine your main code is a tree trunk. A branch is like a smaller offshoot where you can work on new features without affecting the main code.
- Your main branch (usually called
main
ormaster
) holds stable code. - You create branches to develop new features, fix bugs, or experiment.
- Once your work is ready, you merge the branch back into the main line.
Why Use Branches?
- Avoids breaking the working project
- Encourages better collaboration
- Makes it easier to track specific features or fixes
- Allows testing features independently
Creating a New Branch
Let’s say you want to add a contact form to your website:
git branch contact-form
This creates a new branch but doesn’t switch to it yet.
To move to that branch:
git checkout contact-form
Alternatively, do both in one command:
git checkout -b contact-form
You are now in a new “copy” of your project where you can freely make changes.
Making Changes in the Branch
You can now create or modify files. For example:
echo "Contact us at hello@example.com" > contact.html
git add contact.html
git commit -m "Add contact form page"
echo "Contact us at hello@example.com" > contact.html
git add contact.html
git commit -m "Add contact form page"
These changes exist only in the contact-form
branch — your main
branch remains untouched.
Switching Between Branches
You can switch back to the main branch anytime:
git checkout main
Merging a Branch into Main
Once your work is done and tested, go back to the main branch:
git checkout main
Now merge your feature branch:
git merge contact-form
🎉 Git will add the changes from contact-form
into main
.
👉 Ask our Educational Tutor now!
What if There’s a Conflict?
Sometimes two branches change the same line in a file — that’s a merge conflict. Git will pause and ask you to manually resolve the conflict.
- Open the file, look for
<<<<<<<
,=======
, and>>>>>>>
. - Choose which version to keep.
- After fixing, run:
git add [filename]
git commit -m "Resolve merge conflict"
Deleting a Merged Branch
Once your feature is merged, you can delete the branch:
git branch -d contact-form
Don’t worry — the changes are now part of main
.
🔁 Summary: Common Branching Commands
Command | Description |
---|---|
git branch | List all branches |
git branch [name] | Create a new branch |
git checkout [name] | Switch to a branch |
git checkout -b [name] | Create and switch to a branch |
git merge [name] | Merge branch into current |
git branch -d [name] | Delete a branch |
Using branches helps you organize your work, reduce errors, and collaborate like a pro.