Merge a Specific Commit in Git

This article will discuss how we can merge a specific commit in Git. This is handy when we want to move a commit of our choosing to a different branch while working on a project.

Let’s jump right in.

Merge a Specific Commit in Git

Below are the four steps we use when merging a specific commit in Git.

  • Fetch Changes from Remote Repository

    We use the git fetch command to download any changes made to the remote repository to our local machine.

    git fetch
    

    Note that the above command imports only the changes and stores them in your local repo. It does not merge the commits.

  • Confirm the Commit Hash
You will need the commit hash of the commit you want to merge. Follow these steps.

Switch to the branch containing the commit you desire.

```bash
git checkout <branch-name>
```

Run the `git log` command to see a list of the commits in that branch. Use the `--oneline` argument for a compact view.

```bash
git log --oneline
```
  • Merge the Commit

    Note down the hash of the commit you want to merge and switch to the destination branch. Use the git checkout command.

```bash
git checkout <branch-name>
```

Use the `git cherry-pick` command to merge the commit you desire with your current branch.

```bash
git cherry-pick <sha1-commit-hash>
```
  • Push the Branch

    We can now run the git push command to push the changes to the remote repository.

    git push origin <branch-name>
    

    It is worth noting that we use the git merge command to combine two Git branches. We can also use the command to merge multiple commits to one history.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Git Cherry-Pick

  • Cherry-Pick Merge Commit in Git