gitgithub

Restore deleted file with history in git


How to restore an accidentally deleted file and folder in git after push. Below is the scenario.

  1. Accidentally deleted a folder which has a single file and made a bunch of changes to other files.
  2. Now, pushed all these changes. So this push has the deleted folder along with other changed files.
  3. On top of this, there were a few more pushes.

Now, can I restore the deleted file, along with history and then push back to repo.


Solution

  • Sure, just check it out from a commit where it existed. If the commit that deleted the file is the tip of whatever you have currently checked out, that’s HEAD^ (the commit before last):

    git checkout HEAD^ -- path/to/file
    

    Then you can commit and push it.