How to Selectively Merge Changes From Different Branches in Git

John Wachira Feb 02, 2024
How to Selectively Merge Changes From Different Branches in Git

This article will discuss merging specific changes from one branch to another. As we know, when merging branches, Git merges all files without exception.

You may find yourself in a scenario where you have some commits in a branch, and you must pick a few and merge them onto another branch. Let us see how we can go around this.

Selectively Merge Changes From Different Branches in Git

For better understanding, we will simulate a scenario where we need to merge some commits from one branch to another. Here is how we will go around it.

Example:

In our local repository, Delftscopetech, we have two branches, namely:

  1. Dev_Branch
  2. Main

To make things as practical as possible, we will assume that we found some bugs in our project that needed fixing. After fixing the bugs, we realized we were checked out on the Dev_Branch branch instead of the Main branch.

A normal merge will break our project. What do we do?

In such a scenario, we will first run the git log command to display our commit history in the Dev_Branch. Make sure you are in the branch containing the changes you need.

$ git checkout Dev_Branch

Here is our commit history:

$ git log --oneline

Commit History in Dev_Branch

We will then identify the commits we want to merge to our Main branch. Here is the commit history in our Main branch:

$ git checkout Main
$ git log --oneline

Commit History in Main Branch

We can see that our Main branch does not have the following commits:

  1. edcb8ae Second Bug Fix
  2. cefb7bb First Bug Fix

To merge the two commits, we will use the git cherry-pick command and feed the commit ids for the two commits. Make sure you are checked out in the branch you want to merge to, in our case, the Main branch.

$ git checkout Main

We can now run the cherry-pick as shown below:

$ git cherry-pick edcb8ae cefb7bb

Output:

Git Selective Merge Output

If you do not have merge conflicts, you should get something similar to the output above. Let us confirm the merge.

$ git log --oneline

Confirm the Merge

The output shows that Git has created two new commits with different commit ids but the same description. We can now push the branch to the remote repo by running the git push command as shown below:

$ git push origin Main

To summarize, we can merge selectively in Git thanks to the git cherry-pick command. All you need is the commit id for the change you want to merge and ensure you are checked out in the right branch.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Commit

Related Article - Git Merge