95

How can I check out a particular version of one file in git?

I found this mail on the mailing list, which said:

$ git checkout HEAD~43 Makefile
$ git reset Makefile

But I don't understand how to find out 'HEAD~43', if I do a git log aFile, how can I find out which 'HEAD~43' I should use?

And why do I need to run git reset for that file? What does it do?

Jim Puls
  • 79,175
  • 10
  • 73
  • 78
n179911
  • 19,547
  • 46
  • 120
  • 162
  • 1
    "git reset " does exactly the same as "git checkout ". – Jakub Narębski Jul 23 '09 at 20:09
  • 2
    If your question is about HEAD~43 syntax (documented in git-rev-parse), ask about this issue, not about unrelated one you know the answer to. "What does HEAD~45 mean, and how to find particular version of file" – Jakub Narębski Jul 23 '09 at 20:11
  • according to http://www.lt.kernel.org/pub/software/scm/git/docs/v1.6.0.6/git-checkout.html and http://www.lt.kernel.org/pub/software/scm/git/docs/v1.6.0.6/git-reset.html, "git reset " doesn't do exactly the same as "git checkout ": "git reset " reverts in the index from without touching in the working tree, but "git checkout " updates the index for from and then updating in working tree. – yoda Jan 29 '10 at 06:33
  • As T.J. suggested, please mark the answer below as accepted. – Jonathan H Jan 31 '17 at 18:13
  • 1
    Possible duplicate of [Reset or revert a specific file to a specific revision using Git?](http://stackoverflow.com/questions/215718/reset-or-revert-a-specific-file-to-a-specific-revision-using-git) – 1615903 Apr 21 '17 at 09:36

3 Answers3

116

You know what commit (ie: the specific revision) the file belongs to? Then do:

git checkout <commit> <file>

The other command:

git checkout HEAD~N <file>

Is for when you want to get a version of the file from a range back (which I do for nostalgia).

Fake Code Monkey Rashid
  • 13,731
  • 6
  • 37
  • 41
20

HEAD~43 is just treeish, so you can use a hash or a tag. You have to separate treeish from the filename with --, otherwise it is treated as filename. For example.

git checkout v0.45 -- filename
git checkout HEAD^ -- filename
git checkout 16bb1a4eeaa9 -- filename
dhill
  • 3,327
  • 2
  • 19
  • 18
2

HEAD~43 refers to the commit (version) of the file. Instead of that, you can use the commit hash you get from doing git log on the file. If you just want the file, you don't need to run git reset on it; that's only necessary if you want to forward-port the file to the current HEAD.

Jim Puls
  • 79,175
  • 10
  • 73
  • 78