Easy way to restore deleted files with Git

"I deleted that file in the past, but I actually needed it." "I want to modify that deleted program to create a new program." Here's an easy way to recover deleted files in Git.

Git has a history of changes to all files and directories. So all you need to do is know how to revert to the past state and the commit immediately before the one that deleted the file.

Find the commit ID immediately before the commit that deleted the file

You can see past commits with the git log command.

git log
commit 23cd914d4f7087a01a1d23c66edc98026013102d
Author: Kimoto Yuki <kimoto.yuki@google.com>
Date: Wed Nov 25 10:20:34 2020 +0900

    Delete unnecessary XX files

commit a15a73d62711fd9a5469ae7791241a4fd8978537
Author: Kimoto Yuki <kimoto.yuki@google.com>
Date: Wed Nov 25 10:20:34 2020 +0900

    Fix header

If you can find the commit ID "a15a73d ..." before deleting the file immediately, that's OK.

If you erased it a long time ago, it's hard to follow the commit message. In that case, search for the commit message. The commit message needs to be remembered.

git log --grep remove

If you put something like "Delete XX" in the commit message, you can search with this.

Let's get the commit ID of this commit.

commit 23cd914d4f7087a01a1d23c66edc98026013102d
Author: Kimoto Yuki <kimoto.yuki@google.com>
Date: Wed Nov 25 10:20:34 2020 +0900

    Delete unnecessary XX files

In Git, the previous commit ID can be expressed by "commit ID ^".

# Commit ID of the previous commit
23cd914d4f7087a01a1d23c66edc98026013102d ^

Create a branch and check out

Let's create a new branch with git branch from the above commit ID. Here, the name is "old".

git branch old 23cd914d4f7087a01a1d23c66edc98026013102d ^

Do a git checkout to switch branches.

git checkout old

Find out if there is an old file and copy it somewhere. Then go back to the original branch.

Associated Information