gitgit-checkout

Restore a deleted folder in a Git repo


I have deleted all the contents inside a folder and the folder is empty. I still had a copy in my remote repo. But when I did a git pull it didn't put back the deleted files isn't is supposed to do that?

So I did some research and saw that you can revert a file by doing git checkout <revision> -- <name of file>

But that only works on files.

How can I retrieve all the files inside the directory?


Solution

  • Folder was deleted, but not committed yet

    Everything you can do with a file, you can do with a folder too.

    If you've just recently removed the folder but have not yet indexed (git add) the changes, you can undo the changes with one command:

    git checkout -- path/to/folder
    

    If you have already done git add, you should first reset it, and then restore the contents:

    git reset -- path/to/folder
    git checkout -- path/to/folder
    

    Restore the full working tree (not a single folder), but lose all uncommitted changes

    If you've removed the contents of several folders, or made other unwanted changes, you can undo them all at once:

    git checkout --
    

    Folder was deleted and the change was committed some time ago

    First, find the latest commit that had affected the given path:

    git rev-list -n 1 HEAD -- path/to/folder
    

    This command will return the hash of the commit that deleted the file.

    Next, checkout the file from a commit before this one, referring to it using the caret (^) character:

    git checkout <deleting_commit>^ -- path/to/folder
    

    Also, see How do I find and restore a deleted file in a Git repository?