How to Pull Specific Commit From Git Repository

Ashok Chapagai Feb 02, 2024
  1. Using git fetch to Fetch Changes Then Merge Using Commit Hash
  2. Pull Code of Specific Commit to a New Branch
  3. Using git pull With Commit Hash
How to Pull Specific Commit From Git Repository

Sometimes you might want to pull a specific commit from the remote repository into the local repo, and there are several ways to accomplish that. Below, you can find several ways to pull a specific commit from the Git repository.

Using git fetch to Fetch Changes Then Merge Using Commit Hash

Using this, you can fetch the changes from the remote repository and then locate the commit’s hash you want to merge to the local codebase. You can refer to the following steps:

  • Fetch Latest Changes to the Repo
    git fetch remote <branch_name>
    

    The git fetch command fetches the changes from specified <branch_name>.

  • Viewing Git Log to Grab Commit Hash to Merge
    git log
    

    The above command lists all the commits, such as the commit hash, author of the commit, date of commit, and commit message.
    You can fetch all the commits and their respective hashes in one line using the --oneline flag, git log --oneline.

  • Merging the Desired Commit Using the Commit Hash
    git merge <commit_hash>
    

    Finally, the commit you want to merge can be done using the commit hash with the git merge command.

With the above method, all the commits up to the merged commit are also merged. To merge the changes from a single commit, you can, however, use git cherry-pick as:

git cherry-pick <commit_hash>

Pull Code of Specific Commit to a New Branch

If you want to pull the changes from the commit and check out to a new branch, you can use a single command to achieve that.

git checkout -b <new_branch_name> <commit_hash>

We can retrieve the commit hash with the git log command mentioned above.

Using git pull With Commit Hash

This step is similar to the one mentioned in the first method up to the second step. After doing as mentioned, the second step (after running git fetch and git log to see the commit hash).

git pull origin <commit_hash>

With the usage of the above command, you can pull all the changes from mentioned commits’ hash.

Here, git pull combines git fetch and git merge.

Ashok Chapagai avatar Ashok Chapagai avatar

Ashok is an avid learner and senior software engineer with a keen interest in cyber security. He loves articulating his experience with words to wider audience.

LinkedIn GitHub