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.
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.
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.
ls
command to ensure that the file is restored.The entire process is shown using a state diagram.
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.
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
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")
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
ls
command to ensure that the deleted file is recovered.The above process is displayed using a state diagram.