How to restore deleted files in Git?

In this tutorial, you will learn how to recover or undo deleted files in Git.

The prerequisite for restoring deleted file is: Git must be tracking the file.

Scenario 1: When a file is deleted using rm command

  1. The very first command that you must run is git status command. This command will show you that the file is in a deleted state.

    On branch master
    Changes not staged for commit:
      (use "git add/rm ..." to update what will be committed)
      (use "git checkout -- ..." to discard changes in working directory)
    
            deleted:    index.html
    
    no changes added to commit (use "git add" and/or "git commit -a")

    Here, index.html is in the deleted state.

  2. After checking the state of the file, run git checkout -- filename command. This command will restore deleted file to the working directory. In our case, the file is index.html so the command will be git checkout -- index.html

    There is a space before and after a pair of dashes.

  3. In the end, run ls command to ensure that the file is restored.

The entire process is shown using a state diagram.

git restore deleted file

Scenario 2: When a file is deleted using git rm command

  1. Run git status command to ensure that the deleted file is in a staging area.

    On branch master
    Changes to be committed:
      (use "git reset HEAD ..." to unstage)
    
            deleted:    index.html

    Here, index.html is in the staging area.

  2. After this, you must run git reset HEAD filename command to move the file from a staging area to deleted state. In our case, command will be git reset HEAD index.html
  3. On running git status command, you will find that the file is in the deleted state.

    On branch master
    Changes not staged for commit:
      (use "git add/rm ..." to update what will be committed)
      (use "git checkout -- ..." to discard changes in working directory)
    
            deleted:    index.html
    
    no changes added to commit (use "git add" and/or "git commit -a")
  4. Enter git checkout -- filename command to restore the deleted file. Here, we have to recover index.html file so the command will be git checkout -- index.html
  5. Finally, run ls command to ensure that the deleted file is recovered.

The above process is displayed using a state diagram.

git undo deleted file