I added a directory to a local git repo using git add and then accidentally did git rm -rf (without committing before). Is there some way of recovering the files from this directory?
            Asked
            
        
        
            Active
            
        
            Viewed 4,377 times
        
    2
            
            
         
    
    
        Grzegorz Chrupała
        
- 3,053
- 17
- 24
- 
                    Wrote you a full answer below. – CodeWizard Mar 22 '16 at 19:01
- 
                    It seems that You need to use some data recovery software if You deleted whole dir (including .git dir) - try to not place new files on dusk (especially in this dir) until You try to recover data. http://superuser.com/questions/279733/undo-an-rm-rf-command – barat Mar 22 '16 at 19:22
2 Answers
11
            Yes you can,
Read this: How to undo changes in Git.
Once you add files to git they are started to be tracked and they are stored under the .git folder.
In they were just added and never commited they are refereed as dangling objects. Those object can be recovered.
Ho to restore dangling objects?
First we have to find them out
git fsck --full
Once you have the list of those object you need to view them and to find out which ones you need.
# Print out the content of the Object
git cat-file -p <SHA-1>
# If the object is a file you will simply see its content,
# Copy it and save it in a new file.
 
    
    
        Community
        
- 1
- 1
 
    
    
        CodeWizard
        
- 128,036
- 21
- 144
- 167
- 
                    1Glad to help, read the attached post about the HEAD, it will teach you new things i assume. – CodeWizard Mar 22 '16 at 19:22
- 
                    1
- 
                    1
2
            
            
        Here is my recover.py utility, which will create a file for each hash:
enter code here
import subprocess
hashes=["01b6a7f272375bc99d98be0068c273b5bc4e9ff6",
"03620d7b53c8a48314c25a3ecdbe369553b01340","PUTYOUR HASHEZ HERE"]
for myhash in hashes:
    print "HASH", myhash
    bashCommand = "git cat-file -p "+ myhash
    process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()
    file = open("recover/"+myhash, "w")
    file.write(output)
    file.close()
This will write to recover folder all files you killed with git
 
    
    
        Dmitry Yudin
        
- 1,033
- 1
- 10
- 31

