Grab any file from a past commit in Git

Have you ever been working on a project and you realize that at some point you altered a file for the worse? The code was fine before, but you went in and changed it, thinking it was an improvement, and now you want it back?

If you’ve been tracking it with Git, as you really should with any project, it’s easy to hop in your time machine and retrieve the file. Simply enter the following command:

git log --follow -- public/functions/main.php

This will show you a history of commits where that file was changed, along with the author of the commit, the date of the commit, and the commit message. You’ll see something like this:

Let’s say looking back at the history of this file, you decide that “update all functions in main.php” is the last commit before you made the bad changes to file.php. Simply run the following command:

git checkout b43123 public/functions/main.php

This does exactly what it looks like, it checks out the file “main.php” from the commit starting with hash b43123. This version of main.php is now in your working directory. Review and test it, and if you’re happy with it, commit it and push it back to the tip of your branch. Voila!

Leave a Reply

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