Restore deleted file not staged in git


I accidentally removed the entire directory of my source code…with a nice rm -r. I know, really bad; but fortunately, I had a git repo in the containing directory. Thus, git has a huge list of unstaged changes of deleted files. For example:

"deleted:   src/caronmonitor/" 

How do I get these files back? There is advice all over the web to do:

git checkout file


git revert <commit>

But as I understand that will restore the file to it’s state at the last commit. I don’t want to go back to the last commit but instead go back to right before the delete operation. I can look in the gitk and see my files as they were before the delete; thus this must be possible.


Not, GIT does not do any magic. If you did not staged or commited your changes then those are gone.
You can see deletions but you can only revert those to last state that you told GIT to remember it for you.

You have to tell explicitly GIT to remember your changes by staging and commiting.

So if you have file.txt in your repository with content:

    int main(argc[] args){

This was your last change that was commited or staged.

Now you edit file.txt to contain something like:

int main(argc[] args){
 System.out.println("Hey I can print more lines");

You save your file, close editor, do nothing with git and do rm -r
Now the file is there, and git has reference to file and that it was deleted but content of this file in git is only:

    int main(argc[] args){

Answered By – Mateusz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published