Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo delete in GIT

I made something very stupid. I made a commit using git commit (file edits + new files) (C). Then I made amend last commit. Then I deleted all files recursively (!) using git rm -r Then I made another git commit (C).

A-B-C
    ↑
  master

Is there any way to undelete the files but keep the changes I had in my first commit? (C) I'd rather do not go back to (B). I tried git reset --soft head^, so then the git status lists files I deleted, then I did git checkout, but still no luck. I don't even know if it's possible.

like image 365
Nately Avatar asked Feb 28 '12 06:02

Nately


People also ask

How do you undo a delete in git?

If you have deleted the file and already committed the changes, you need to use the ` git checkout` command to restore the file. First, you need to find out the checksum of the commit that deleted the file, and then check out the file from the previous commit.

How do I undo a commit delete?

In order to undo the last commit and discard all changes in the working directory and index, execute the “git reset” command with the “–hard” option and specify the commit before HEAD (“HEAD~1”).

Can you recover a deleted branch git?

A deleted Git branch can be restored at any time, regardless of when it was deleted. Open your repo on the web and select the Branches view. Search for the exact branch name using the Search all branches box in the upper right. Click the link to Search for exact match in deleted branches.


2 Answers

Do yourself a favour and do not do git checkout <hash> like the other answer suggests and go into more problems.

IF you have deleted file from your working directory and not committed the changes yet, do:

git checkout -f 

CAUTION: commit uncommitted files before executing this command, otherwise you're going to lose them all

The deleted files should be back again.

If not and if you can find the commit that you want ( C, etc. - your question is not clear ) from git reflog, just do git reset --hard <hash from reflog> and you should be all set.

like image 67
manojlds Avatar answered Oct 23 '22 18:10

manojlds


If I understood you correctly you rewrote commit C. So the original commit, let's call it C1 is not accessible from your commit graph, but it is still there (git keeps all commits for a while). Use git reflog to get the commit hash and git checkout <hash> or another appropriate command to get to the old state C1.

like image 21
Sascha Avatar answered Oct 23 '22 19:10

Sascha