How to Merge a Specific Commit in Git

There are cases when developers need to move a specific commit to another branch of the git repository. Below, you will find out how to do it by merging a particular commit.

Watch a course Git & GitHub - The Practical Guide

Steps to merging a commit

Now let’s take these 5 steps below and get the job done appropriately:

Fetch the changes from the remote

First of all, you need to download all the changes from the remote by running the git fetch command:

git fetch
If you work with multiple remotes, then refer to How to Fetch All Git Branches.

Find the appropriate commit hash

If you don't know the hash of the commit you want to merge, then you can find it by following the steps below:

  • With the first step, checkout to the branch, containing that commit:
    git checkout <branch-name>
  • Then, run the git log command with the --oneline option to get the compact view of the commits. Afterwards, you can find the appropriate commit hash.
    git log --oneline

Merge a specific commit

Now, it is necessary to check out to the branch where you want to merge the specific commit:

git checkout <branch-name>

Run the git cherry pick command to merge the commit with your branch:

git cherry-pick <sha1-commit-hash>

Push the branch

The final step is pushing the branch by running the git push command (suppose, the name of remote is origin, which is by default):

git push origin <branch-name>

The Usage of Git Merge

The git merge command is targeted at combining two branches. You can also use it for merging several commits into a single history. The merge commits involve two parent commits. Every time a new merge commit is made, git runs an automate merging of different histories. But it will not integrate the data changed in both of the histories. It is known as “version control conflict”.

Merge Conflicts

The merge conflicts happen when different developers edit the same file or when one of them deletes a file on which another developer is making changes. With the purpose of solving such kind of problems, isolated branches are created.

Unlike other version control systems, Git makes it easier to merge. It can also integrate new changes mechanically. But when conflicts occur, Git won’t be able to find out automatically which of the versions is correct. Hence, the process of merging will be stopped by Git, because of the conflict.