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

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

git reset --hard 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

其他回答

我遇到了类似的问题。解决方案是使用gitlog来查找本地提交的版本与远程提交的版本不同。(例如,版本为3c74a11530697214cbcc4b7b98bf7a65952a34ec)。

然后使用git reset-hard 3c74a11530697214cbcc4b7b98bf7a65952a34ec还原更改。

尝试此操作以还原本地分支中未提交的所有更改

$ git reset --hard HEAD

但如果您看到这样的错误:

fatal: Unable to create '/directory/for/your/project/.git/index.lock': File exists.

您可以导航到“.git”文件夹,然后删除index.lock文件:

$ cd /directory/for/your/project/.git/
$ rm index.lock

最后,再次运行命令:

$ git reset --hard HEAD

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

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

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

从工作副本根目录运行。

如果您在顶级项目目录中,请尝试以下操作:

git restore .

如果没有,则使用:

git restore :/

如果要还原子集的本地更改:

使用top pathspec magic还原所有工作树文件:git restore:/还原当前目录中的所有文件:gitrestore。文件类型(例如所有C源文件):git restore“*.C”

有关详细信息,请参阅git restore文档。

要删除未跟踪的文件:gitclean-f

我搜索了一个类似的问题,

想要放弃本地提交:

克隆了存储库(gitclone)切换到dev分支(git checkout dev)做了几次提交(gitcommit-m“commit 1”)但决定放弃这些本地提交,返回远程(origin/dev)

以下情况也是如此:

git reset --hard origin/dev

检查:

git status  

        On branch dev  
        Your branch is up-to-date with 'origin/dev'.  
        nothing to commit, working tree clean  

现在,本地提交丢失,返回到最初的克隆状态,即上面的第1点。