Working with git – How to Restore a Deleted File

Mike BerrymanThe scenario: you deleted a file and now you realize you still need it. So what do you do? Here are the steps to get back a file that was deleted several commits in the past.

Untitled-1.jpg

  1. Find the commit that the file was deleted in
  2. Checkout the version of the deleted file from the commit just before it was deleted.  On other words, the last when when it existed.
  3. Add the restored file and commit to your repository
In this simple example, I deleted app3.js two commits back.
But if the delete was done farther back (or maybe it is not clear from the commit message),  and you don’t know which commit the file was deleted, this is how you can find that out:
  • git rev-list -n 1 HEAD — “app3.js”
This tells us the commit in which the file was deleted.  To restore the deleted file, we need to do a git checkout and specify the commit prior to the delete commit.  This can be done with:
  • git checkout f5394fc841d35f004b368dff438dccf4607e1bec^ — “app3.js”

The “^” character following the commit hash tells git to use the parent of that commit, which in this case would be last commit that app3.js existed in.

As you can see, git status shows us that app3.js is now back and is showing as an unstaged, new file.  Just do “git add app3.js” and commit.  Victory!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s