How can I undo git reset --hard HEAD~1?

2018-12-31 04:10发布

Is it possible to undo the changes caused by the following command? If so, how?

git reset --hard HEAD~1

13条回答
孤独寂梦人
2楼-- · 2018-12-31 04:31

It is possible to recover it if Git hasn't garbage collected yet.

Get an overview of dangling commits with fsck:

$ git fsck --lost-found
dangling commit b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf

Recover the dangling commit with rebase:

$ git rebase b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf
查看更多
若你有天会懂
3楼-- · 2018-12-31 04:32

The answer is hidden in the detailed response above, you can simply do:

$> git reset --hard HEAD@{1}

(See the output of git reflog show)

查看更多
余生请多指教
4楼-- · 2018-12-31 04:32

as far as i know, --hard will discards uncommitted changes. Since these aren't tracked by git. but you can undo the discarded commit.

$ git reflog

will lists:

b0d059c HEAD@{0}: reset: moving to HEAD~1
4bac331 HEAD@{1}: commit: added level introduction....
....

where 4bac331 is the discarded commit.

Now just move the head to that commit::

$ git reset --hard 4bac331
查看更多
冷夜・残月
5楼-- · 2018-12-31 04:32

I've just did a hard reset on wrong project. What saved my life was Eclipse's local history. IntelliJ Idea is said to have one, too, and so may your editor, it's worth checking:

  1. Eclipse help topic on Local History
  2. http://wiki.eclipse.org/FAQ_Where_is_the_workspace_local_history_stored%3F
查看更多
裙下三千臣
6楼-- · 2018-12-31 04:33

Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs.

$ git init
Initialized empty Git repository in .git/

$ echo "testing reset" > file1
$ git add file1
$ git commit -m 'added file1'
Created initial commit 1a75c1d: added file1
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 file1

$ echo "added new file" > file2
$ git add file2
$ git commit -m 'added file2'
Created commit f6e5064: added file2
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 file2

$ git reset --hard HEAD^
HEAD is now at 1a75c1d... added file1

$ cat file2
cat: file2: No such file or directory

$ git reflog
1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD
f6e5064... HEAD@{1}: commit: added file2

$ git reset --hard f6e5064
HEAD is now at f6e5064... added file2

$ cat file2
added new file

You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog.

查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 04:33

What you want to do is to specify the sha1 of the commit you want to restore to. You can get the sha1 by examining the reflog (git reflog) and then doing

git reset --hard <sha1 of desired commit>

But don't wait too long... after a few weeks git will eventually see that commit as unreferenced and delete all the blobs.

查看更多
登录 后发表回答