Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git fetch a specific commit by hash

Tags:

git

Git allows to fetch from any given remote and reference, for example

git fetch <remote-url> <reference> 

So that those given commits are available without having to add remotes or creating branches.

This however only works for references, like branch names or tags, but not for specific hashes and thus commits that are not referenced directly anywhere.

Is there a way to fetch a specific commit from a remote?

like image 782
Maic López Sáenz Avatar asked Jan 17 '13 00:01

Maic López Sáenz


People also ask

How do I pull only a specific commit?

Go to either the git log or the GitHub UI and grab the unique commit hashes for each of the commits that you want. "Cherry pick" the commits you want into this branch. Run this command: git cherry-pick super-long-hash-here . That will pull just this commit into your current branch.

How do you pull from a commit hash?

To pull up a list of your commits and their associated hashes, you can run the git log command. To checkout a previous commit, you will use the Git checkout command followed by the commit hash you retrieved from your Git log.

How do I pull a specific commit in git?

First clone the latest repo from git (if haven't) using git clone <HTTPs link of the project> (or using SSH) then go to the desire branch using git checkout <branch name> . Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name> . That's all.


2 Answers

As today I tried:

git fetch origin <commit-hash> 

And it works like a charm! (git version 2.20.1)

Just be sure the <commit-hash> is the full length reference

like image 169
crgarridos Avatar answered Oct 02 '22 11:10

crgarridos


See "Pull a specific commit from a remote git repository":
With Git 2.5 (July 2015), you will be able to do:

git fetch --depth=1 <a/remote/repo.git> <full-lenght SHA1> git cat-file commit $SHA1 

If the SHA1 is "reachable" from one of the branch tips of the remote repo, then you can fetch it.

Caveats:

  • you need a Git 2.5 remote repo server though, which will handle the uploadpack.allowReachableSHA1InWant config (and you need that config to be set to true, in order to allow a single commit fetch).
  • And, as illustrated in crgarridos's answer, you need the full SHA1, and you cannot use git rev-parse, since you don't have all the commits, as noted by Jim Hurne in the comments.
like image 27
VonC Avatar answered Oct 02 '22 13:10

VonC