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
andfeature-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:
- Push your branch to GitHub (if it’s not already there):
git push origin feature-branch
- Go to your repository on GitHub.
- 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
. - Review the changes.
- Click “Create pull request”.
- Once approved (if using code review), click “Merge pull request”.
- Confirm by clicking “Confirm merge”.
- Optionally, delete the feature branch after merging.
✅ Option 2: Merge Locally Using Git
If you prefer the command line:
Step-by-Step:
- Fetch the latest code from the remote:
git fetch origin
- Checkout the main branch:
git checkout main
- Make sure it’s up to date:
git pull origin main
- Merge your feature branch:
git merge feature-branch
- Resolve any conflicts if necessary.
- 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
Method | Description |
---|---|
GitHub UI | Open pull request → Review → Merge |
Git (CLI) | Use git merge and git push |
Best practice | Use 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.