Git: checkout / get back a deleted file w/ commit id

Problem: You've deleted a file and want to get it back but you can only remember just a part of the file name or even just a part of the comment you've assigned to the respective Git commit.

Now you want this file back which you've deleted a while ago.

Solution:


1. Get the id of the commit where the file was deleted using one of the ways below.

  • git log --grep=word
  • git log -Sword
  • git log | grep --context=5 word
  • git log --stat | grep --context=5 word # recommended if you hardly remember anything
2. You should get something like: 
commit bfe68bd117e1091c96d2976c99b3bcc8310bebe7Author: Alexander Orlov <alexander.orlov@loxal.net>Date:   Thu May 12 23:44:27 2011 +0200
    replaced deprecated GWT class    - gwtI18nKeySync.sh, an outdated (?, replaced by a Maven goal) I18n generation script
commit 3ea4e3af253ac6fd1691ff6bb89c964f54802302Author: Alexander Orlov <alexander.orlov@loxal.net>Date:   Thu May 12 22:10:22 2011 +0200
3. Now using the commit id bfe68bd117e1091c96d2976c99b3bcc8310bebe7 do:


git checkout bfe68bd117e1091c96d2976c99b3bcc8310bebe7^1 yourFile.java


As the commit id references the commit where the file was already deleted you need to reference the commit just before bfe68b which you can do by appending ^1. This means: give me the commit just before bfe68b.

Comments

Popular posts from this blog

Tuning ext4 for performance with emphasis on SSD usage

Rust’s impact on the industry

Brandan Eich on WebAssembly, Web Workers, and Decorators