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:
Dev_Branch
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
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
We can see that our Main
branch does not have the following commits:
edcb8ae
Second Bug Fixcefb7bb
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:
If you do not have merge conflicts, you should get something similar to the output above. Let us confirm the merge.
$ git log --oneline
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.
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.
LinkedInRelated Article - Git Commit
- How to Get Current Commit in Git
- How to List Commits in Git
- How to Have Git Add and Git Commit in One Command
- How to git add, git commit, and git push in One Command
- How to Commit Current Changes to a Different Branch in Git
- How to Exit the Commit Message Editor