How do I undelete a file after git rm and pushing to github?
Asked Answered
H

5

28

I recently cloned a repository on my local machine and then did a git remove on one of the files and pushed those changes back to the github repository. My question is how do I restore that file back on the original github repository?

Herbage answered 7/10, 2013 at 0:3 Comment(0)
O
35

Let's assume the file "undelete.sh" was accidentally removed.

Then get the hash of the commit in which this file is deleted:

git rev-list -n 1 HEAD -- undelete.sh

Which gives you the hash of the deletion:

ae85c23372a8a45b788ed857800b3b424b1c15f8

Now you can checkout the version of the file before the deletion:

git checkout ae85c23372a8a45b788ed857800b3b424b1c15f8^ -- undelete.sh

And you should have the file back. You may add, commit and push it to the repository.

(source)

Ormand answered 13/8, 2019 at 23:31 Comment(0)
B
34

If you can find a previous commit abcd that has the deleted file, then you can use

git checkout abcd file-to-restore

to restore it. You'll need to commit the file again.

Busk answered 7/10, 2013 at 0:28 Comment(1)
I had to add a ^ to the commit to get this to work - idea from an answer below. so git checkout abcd^ file-to-restoreCutshall
L
5

Other solutions did not worked for me. This is how I did it.

This is how I get the commit hash. (Copied from above)

git rev-list -n 1 HEAD -- src/main/java/runner/Main.java

which gave me

6009ff608bc580cf38baf5fa67e232c8bd20c5a7

And, this is how I restored it.

git checkout 6009ff608bc580cf38baf5fa67e232c8bd20c5a7~1 src/main/java/runner/Main.java
Lowbrow answered 25/11, 2020 at 9:44 Comment(1)
this is the only approach which worked for me. Not sure why the ones with more upvotes didn't. My lack of knowledge is probably the problem :)Prokopyevsk
W
2

1.If the deleted file is in your .gitignore,then you can remove it in .gitignore and git add it again.

2.You can just use git reset 'commit id contains your deleted file' then merge and push it again.

Water answered 7/10, 2013 at 4:30 Comment(0)
R
-1

You should use git reset HEAD~ and then use git checkout -- <filename> to restore deleted files.

Raasch answered 20/6, 2019 at 1:36 Comment(1)
You are assuming the deletion was made in previous commit, what if it was deleted long time ago.Archaize

© 2022 - 2024 — McMap. All rights reserved.