How to Merge a Branch into Master (Main) on GitHub

Merging branches is a core part of collaborative development in Git. Whether you’re integrating a new feature, fixing a bug, or finalizing a release, you’ll often need to merge your working branch into the main production branch—typically named main or master.

In this guide, you’ll learn how to merge a branch into the main (or master) branch using both GitHub’s web interface and Git commands.


🧭 Prerequisites

  • A GitHub repository with at least two branches (e.g., main and feature-branch)
  • Proper permissions (write access or admin rights)

✅ Option 1: Merge via GitHub Web Interface (Pull Request)

This is the recommended and most collaborative approach.

Step-by-Step:

  1. Push your branch to GitHub (if it’s not already there): git push origin feature-branch
  2. Go to your repository on GitHub.
  3. GitHub will usually show a “Compare & pull request” button. Click it. Or go to Pull requests > New Pull Request and select your branch to merge into main.
  4. Review the changes.
  5. Click “Create pull request”.
  6. Once approved (if using code review), click “Merge pull request”.
  7. Confirm by clicking “Confirm merge”.
  8. Optionally, delete the feature branch after merging.

✅ Option 2: Merge Locally Using Git

If you prefer the command line:

Step-by-Step:

  1. Fetch the latest code from the remote: git fetch origin
  2. Checkout the main branch: git checkout main
  3. Make sure it’s up to date: git pull origin main
  4. Merge your feature branch: git merge feature-branch
  5. Resolve any conflicts if necessary.
  6. Push the merged changes back to GitHub: git push origin main

🔄 Fast-Forward vs Merge Commit

  • If no other changes happened on main, Git may do a fast-forward merge (no merge commit).
  • If changes occurred on both branches, Git will create a merge commit.

You can force one behavior over the other with flags like --no-ff or --ff-only.


📝 Best Practices

  • Always pull the latest changes before merging.
  • Test your changes thoroughly before merging into main.
  • Use pull requests for visibility and code review.
  • Clean up old branches after merging.

Summary

MethodDescription
GitHub UIOpen pull request → Review → Merge
Git (CLI)Use git merge and git push
Best practiceUse PRs with reviews for better collaboration

Merging branches is a safe and efficient way to combine changes in Git. Whether through the GitHub interface or via command line, following these steps will ensure a smooth and error-free merge into your main branch.

Sharing Is Caring:

Leave a Comment