我运行了git状态,它告诉我一切都是最新的,没有本地更改。

然后我做了几次连续的改变,意识到我想扔掉一切,回到原来的状态。这个命令能帮我吗?

git reset --hard HEAD

当前回答

在阅读了一堆答案并尝试之后,我发现了各种边缘情况,这意味着有时它们无法完全清理工作副本。

这是我目前使用的bash脚本,它一直有效。

#!/bin/sh
git reset --hard
git clean -f -d
git checkout HEAD

从工作副本根目录运行。

其他回答

查看git-relog。它将列出它记住的所有状态(默认为30天),您只需签出您想要的状态即可。例如:

$ git init > /dev/null
$ touch a
$ git add .
$ git commit -m"Add file a" > /dev/null
$ echo 'foo' >> a
$ git commit -a -m"Append foo to a" > /dev/null
$ for i in b c d e; do echo $i >>a; git commit -a -m"Append $i to a" ;done > /dev/null
$ git reset --hard HEAD^^ > /dev/null
$ cat a
foo
b
c
$ git reflog
145c322 HEAD@{0}: HEAD^^: updating HEAD
ae7c2b3 HEAD@{1}: commit: Append e to a
fdf2c5e HEAD@{2}: commit: Append d to a
145c322 HEAD@{3}: commit: Append c to a
363e22a HEAD@{4}: commit: Append b to a
fa26c43 HEAD@{5}: commit: Append foo to a
0a392a5 HEAD@{6}: commit (initial): Add file a
$ git reset --hard HEAD@{2}
HEAD is now at fdf2c5e Append d to a
$ cat a
foo
b
c
d

这个问题更多的是关于更广泛的存储库重置/恢复,但如果您对恢复单个更改感兴趣,我在这里添加了类似的答案:

https://stackoverflow.com/a/60890371/2338477

问题解答:

如何恢复git历史记录中保留或不保留更改的单个更改如何返回到旧版本以从相同状态重新启动

简单地执行-

git stash

它将删除所有本地更改。您也可以稍后通过执行-

git stash apply 

在此处添加另一个选项。

我指的是标题:还原本地更改。它还可以应用于未准备提交的更改。

在这种情况下,您可以使用:

git restore <file>

返回到以前的状态。

前方危险:(请阅读评论。执行我的回答中提出的命令可能会删除更多内容)

完全删除所有文件,包括我必须运行的目录

git clean -f -d