Thoughts, information and reflections about technology

How to retrieve a single file from a past commit in Git.

I needed to retrieve a single file from an earlier commit from a git repository that had been inadvertently deleted. The repository was simply a series of commits with no branches. (this still should work if you have branches). I was committing to a local repository and then pushing to dropbox. This example shows how to pull a file from the local repository. 
The first step is to identify the hash of the commit where the file exists. I use Git Gui for windows which provides an easier to use graphical interface. 
The first step is to go to Repository, View Master’s History.
Look for the date where you think that the file you want existed. Click on “Tree” to see the file names in the bottom right. When you have confirmed that the file exists in the commit you are viewing, copy the SHA1 ID.
I navigated in Windows  Explorer  to my project and chose “Git Bash Here” from the right click context menu
The command was
git archive –format zip -9 71b646066ada70a45c363853f6dd03ca4099ef89 HomePg_MainImages.gif >
  • git The git command
  • archive Archive parameter for git.
  • –format zip -9   Set the format to TAR or ZIP. Not sure what the -9 does NOTE – there are Two dashes before format
  • 71b646066ada70a45c363853f6dd03ca4099ef89 Either HEAD or the hash of the commit you want to retrieve from. HEAD is the latest commit.
  • HomePg_MainImages.gif The name of the file I wanted to retrieve
  • >         Redirect output to a file
  • File name of the resulting zip file. Case Counts.
If I look at the project, I now see that a zip file was created.

That zip file contains the file I extracted from the Git repository


That file can be copied and pasted back into your project.
In summary
  • If you are using git and doing regular commits, it is possible to pull a single file from a previous commit.
  • The process is a little tedious.
  • Find the commit where the file you want existed.
  • Copy the hash
  • Go to the appropriate folder, probably the project itself
  • Run the command as shown above
  • Look for the Zip or Tar file and then copy and paste the file you need.
  • Hint – It might be easier to construct the command in something like notepad and then paste it into Git Bash

Similar Posts:

No tags for this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact me
Recent Comments