getting an old file in git from a directory than no longer exists

Some time ago, I had deleted a file in git along with renaming the directory it was in. I had wanted to rename the file rather than delete it. So now I needed it back. This took a few steps so I decided to blog what I did.

Step 1 – find the command to get the commit number for my deletion

I had no idea how to do this so I googled it. A comment on this post was really helpful. On OSX, I ran:

git log --diff-filter=D --summary | sed -n -e '/^commit/h' -e '\:/:{' -e G -e 's/\ncommit \(.*\)/ /gp' -e }

While I understand this, I never would have thought to write it.

This gave me a list of all my commits. Then I added | grep myFileName to it and I got the commit where this file was deleted.

Step 2 – Look at commit details

Next I did a git show to see whether it was me or my teammate that

git show myCommitId

It was me. I didn’t know that at the start. Oops!

Step 3 – Retrieve the file

It is possible to do a git checkout of just one file. However the folder structure doesn’t exist anymore in the latest, so this would be a pain. I decided to just get the file from the github UI. I ran the following (with real values for myRepo and myCommitId).

Then I viewed and downloaded it. Yay. My image file is back.

Step 4 – Commit again

I renamed the file again and added/committed normally.

Done! It’s now like this mistake never happened. Except in git history!

3 thoughts on “getting an old file in git from a directory than no longer exists

  1. Great post. I’m creating a scriptlet around this, since this comes up fairly commonly at work.

    Microsoft Word strikes again!

    It has “helpfully” converted your double dashes (–) to em dashes (–), and it has made your single quotes (‘) into smart quotes (‘’).

    You also have a literal   in your second code snippet.

  2. And your blog software converts my comments in the same way! :-/ Try to clarify:

    Umm, double dashes are the (--). Hopefully the comment about smart quotes are understandable – if not reach out to me. And the other one was regarding an  

  3. Thanks Andrew. I got rid of the literal in the second code snippet. For the first one, WordPress was being way too helpful so I switched to a pre tag. It was right in the HTML i posted originally!

Leave a Reply

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