Search code examples
gitcommitrestore

Restore deleted files from commit


I've just done the following series of steps and I don't know how to recover my files.

  1. git add file.txt
  2. git commit -m "Message"
  3. rm file.txt
  4. git commit -am "Message"

Ideally I should have pushed my changes after step 2 and then delete but I forgot. Is there a way to recover the file?

Many thanks!


Solution

  • You can recover the file from the previous revision with the checkout command:

    git checkout HEAD^ file.txt
    

    If the file has been deleted in an earlier commit (let's assume 229da640), you can recover it by passing commit's sha1, followed by ^:

    git checkout 229da640^ file.txt
    

    If you haven't pushed the commit yet, you might rather want to reset the commit instead:

    git reset --hard HEAD^
    

    This will reset your working tree to the same state as of the previous commit. All changes after the previous commit will be gone.

    If you don't want all changes to be gone, just undo the act of the commit itself, you can reset without the --hard option, and restore the deleted file with:

    git reset HEAD^
    git checkout file.txt