How to revert a “git rm -r .”?

2019-01-03 07:41发布

I accidentely said git rm -r .. How do I recover from this?

I did not commit.

I think all files were marked for deletion and were also physically removed from my local checkout.

EDIT: I could (if I knew the command) revert to the last commit. But it would be a lot better if I could just undo the git rm -r .. Because I am not really sure what I did after the last commit and before the git rm -r ..

标签: git git-rm
11条回答
Viruses.
2楼-- · 2019-01-03 07:55

undo git rm

git rm file             # delete file & update index
git checkout HEAD file  # restore file & index from HEAD

undo git rm -r

git rm -r dir          # delete tracked files in dir & update index
git checkout HEAD dir  # restore file & index from HEAD

undo git rm -rf

git rm -r dir          # delete tracked files & delete uncommitted changes
not possible           # `uncommitted changes` can not be restored.

Uncommitted changes includes not staged changes, staged changes but not committed.

查看更多
神经病院院长
3楼-- · 2019-01-03 08:00

Update:

Since git rm . deletes all files in this and child directories in the working checkout as well as in the index, you need to undo each of these changes:

git reset HEAD . # This undoes the index changes
git checkout .   # This checks out files in this and child directories from the HEAD

This should do what you want. It does not affect parent folders of your checked-out code or index.


Old answer that wasn't:

reset HEAD

will do the trick, and will not erase any uncommitted changes you have made to your files.

after that you need to repeat any git add commands you had queued up.

查看更多
仙女界的扛把子
4楼-- · 2019-01-03 08:00

If you've committed and pushed the changes, you can do this to get the file back

// Replace 2 with the # of commits back before the file was deleted.
git checkout HEAD~2 path/to/file
查看更多
迷人小祖宗
5楼-- · 2019-01-03 08:05
git reset HEAD

Should do it. If you don't have any uncommitted changes that you care about, then

git reset --hard HEAD

should forcibly reset everything to your last commit. If you do have uncommitted changes, but the first command doesn't work, then save your uncommitted changes with git stash:

git stash
git reset --hard HEAD
git stash pop
查看更多
太酷不给撩
6楼-- · 2019-01-03 08:05

Get list commit

git log  --oneline

For example, Stable commit has hash: 45ff319c360cd7bd5442c0fbbe14202d20ccdf81

git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master
查看更多
何必那么认真
7楼-- · 2019-01-03 08:06

There are some good answers already, but I might suggest a little-used syntax that not only works great, but is very explicit in what you want (therefor not scary or mysterious)

git checkout <branch>@{"20 minutes ago"} <filename>
查看更多
登录 后发表回答