27

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?

Maic López Sáenz
  • 8,876
  • 4
  • 40
  • 55

3 Answers3

17

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

crgarridos
  • 6,873
  • 2
  • 35
  • 53
11

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.
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
  • Just like in the other answer here, make sure the $SHA1 is the full length reference. – mkurz May 14 '21 at 08:16
  • 1
    @mkurz Yes, I have edited my answer to include the use of `git rev-parse`, thereby insuring I will *always* use the full-length SHA1 – VonC May 14 '21 at 08:25
  • Unfortunately, `git rev-parse` only works reliably if you have already fetched all of the remote's commits, which of course you do not have if all you want to fetch is a single commit. – Jim Hurne May 21 '21 at 20:37
  • @JimHurne Good point, than you. I have edited the answer accordingly. – VonC May 21 '21 at 21:22
9

No. According to the manual, git fetch wants a refspec, the simplest form of which is a ref, and a bare SHA-1 isn't a ref. I.e., the commit has to have a name (branch, tag) on the remote for you to be able to fetch it.

Fred Foo
  • 328,932
  • 68
  • 689
  • 800