💡 Ask Tutor

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 or master) 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:

Bash
git branch contact-form

This creates a new branch but doesn’t switch to it yet.

To move to that branch:

Bash
git checkout contact-form

Alternatively, do both in one command:

Bash
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:

Bash
echo "Contact us at hello@example.com" > contact.html
git add contact.html
git commit -m "Add contact form page"
Bash
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:

Bash
git checkout main

Merging a Branch into Main

Once your work is done and tested, go back to the main branch:

Bash
git checkout main

Now merge your feature branch:

Bash
git merge contact-form

🎉 Git will add the changes from contact-form into main.

💡 Need help understanding this topic?
👉 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.

  1. Open the file, look for <<<<<<<, =======, and >>>>>>>.
  2. Choose which version to keep.
  3. After fixing, run:
Bash
git add [filename]
git commit -m "Resolve merge conflict"

Deleting a Merged Branch

Once your feature is merged, you can delete the branch:

Bash
git branch -d contact-form

Don’t worry — the changes are now part of main.

🔁 Summary: Common Branching Commands

CommandDescription
git branchList 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.

📘 Next Topic

Forking & Contributing to Open Source →