git,

Restore deleted files in Git

Sep 23, 2022 · 1 min read · Post a comment

There are multiple ways you could recover files in Git. Before we explore them, here’s a list of related posts:

Prerequisites

  • Git

Solution(s)

Deleted a versioned file but didn’t commit

The easiest scenario considering it might was a mistake.

git restore <filename>

or

git checkout <filename>

If it was git add-ed (staged), use:

git restore --staged <filename> && git restore <filename>

or, even better:

git restore --source=HEAD --staged --worktree <filename>

Deleted a versioned file and commit the changes

You changed your mind regarding the deleted file?! I got you covered. Run the following command:

git reset --hard HEAD~1

Deleted a versioned file in some previous commit or branch

Step 1. Find every commit where the file was included:

git reflog -- <filename>

Step 2. Now, you got two options. Either checkout from the latest commit where the file was still there:

git checkout <commit-SHA1> -- <filename>

or, checkout from the commit where the file was initially removed:

git checkout <commit-SHA1>~1 -- <filename>

or, checkout from branch if that might be the case:

git checkout <branch_name> -- <filename>

Deleted a version file, committed and pushed the changes

Last but not least and could be the trickiest one. You will definitely face some problems.

Step 1. Anyway, find the commit removing the file:

git reflog -- <filename>

Step 2. Run:

git revert --no-commit <commit-SHA1>

Conclusion

To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git