How to Merge Two Remote Branches in Git: A Practical Guide

Merging branches is a common and essential task in Git workflows—especially when collaborating with a team on a shared codebase hosted on platforms like GitHub, GitLab, or Bitbucket.

In this guide, we’ll explain how to merge two remote branches in Git using the terminal, ensuring you maintain a clean and conflict-free workflow.


Understanding the Concept

Git operates locally first. This means you can’t directly merge remote branches on the server (e.g., GitHub) from the terminal. Instead, the typical approach is:

  1. Fetch the remote branches to your local machine
  2. Check out one of the branches locally
  3. Merge the other branch into it
  4. Push the merged result back to the remote

Step-by-Step: Merging Two Remote Branches

Let’s say you want to merge feature-branch into develop, and both exist remotely on origin.

Step 1: Fetch All Remote Branches

First, update your local references to the remote branches:

git fetch origin

Step 2: Check Out the Target Branch Locally

Switch to the branch that will receive the changes (in this case, develop):

git checkout develop

If develop does not yet exist locally:

git checkout -b develop origin/develop

Step 3: Merge the Source Branch

Now merge feature-branch into develop:

git merge origin/feature-branch

This pulls in the changes from the remote feature-branch into your local develop branch.


Step 4: Resolve Any Conflicts (If Necessary)

If Git encounters conflicts, it will pause and ask you to resolve them manually. Once resolved:

git add .
git commit

Step 5: Push the Merged Changes to the Remote Repository

Finally, push your updated develop branch back to the remote:

git push origin develop

This updates the remote develop branch with the merged content.


Summary

Here’s a recap of the full process:

git fetch origin
git checkout develop                    # Or: git checkout -b develop origin/develop
git merge origin/feature-branch
# Resolve conflicts if any
git push origin develop

Best Practices

  • Always pull the latest changes before merging.
  • Consider using git pull --rebase to avoid unnecessary merge commits.
  • Test your code locally after merging and before pushing.
  • Use descriptive commit messages for merge commits.
  • Consider opening a pull request (PR) if you’re working in a collaborative environment for code review and CI checks.

Conclusion

Merging remote branches in Git isn’t done directly on the server—it’s a local operation that you push upstream. Understanding this flow gives you greater control over your codebase and helps maintain a stable and well-managed project history.

Sharing Is Caring:

Leave a Comment