Search code examples
gitgit-rm

Git recover files


I added local files to git repo (git add .) and committed.

Then deleted files with git rm * and committed again (second commit). That deleted files both locally and remotely.

Hot to get files back into same local folder from git (from a first commit)?

Thanks.


Solution

  • Since you committed, it doesn't even matter if the local file even exists on your filesystem at the HEAD of your branch, because it is part of the Git history. To retrieve a file from an earlier commit, you may try checking it out:

    git checkout abc123 -- path/to/some/file.ext
    

    where abc123 is the SHA-1 hash of the earlier commit. If you don't know what a SHA-1 hash is, just run git log from the bash, and find the earlier commit along with the hash for that commit.

    Edit:

    If you really want to revert your entire branch to some earlier commit, then a generally safe way to do that is via git revert. So, continuing with the above example, if you wanted to revert the latest commit abc123, you could try:

    git revert abc123
    

    This would add a new commit on top of your branch, which however would just functionally undo whatever that previous HEAD commit was doing. This should leave all the files in your project in their earlier state.