是否可以撤消由以下命令引起的更改?如果是,怎么办?

git reset --hard HEAD~1

当前回答

答案隐藏在上面的详细响应中,您可以简单地执行以下操作:

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

(参见git-relog show的输出)

其他回答

如果Git尚未垃圾收集,则可以恢复它。

使用fsck获取悬空提交的概述:

$ git fsck --lost-found
dangling commit b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf

使用rebase恢复悬空提交:

$ git rebase b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf

制作了一个很小的脚本,以便稍微容易地找到要查找的提交:

git fsck--lost found | grep commit | cut-d“”-f 3 | xargs-i git show \{\}| egrp“^commit |日期:”

是的,它可以用锥子或类似的东西做得更漂亮,但它很简单,我只是需要它。可能会为其他人节省30秒。

git-relog并返回到最后一个HEAD6a56624(HEAD->master)HEAD@{0}:重置:移动到HEAD~31a9bf73 HEAD@{1}:提交:在模型中添加更改生成二进制

注意:此答案仅在使用IntelliJ等IDE时有效

我最近遇到了一个类似的问题,我既没有进行改变,也没有做出承诺。可以选择当地历史。我能够从IntelliJ的本地历史还原更改(参考)。

希望这对某人有所帮助。

帕特·诺茨是正确的。你可以在几天内收回承诺。git只会在大约一个月后收集垃圾,除非您明确告诉它删除更新的blob。

$ 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

您可以在示例中看到,由于硬重置,file2被删除,但当我通过reflog重置时,它被放回原位。