我运行了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

其他回答

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

想要放弃本地提交:

克隆了存储库(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点。

如果您想恢复所有更改并更新当前远程主机(例如,您发现主机HEAD已向前移动,因为您已将其分支,并且您的推送被“拒绝”),您可以使用

git fetch  # will fetch the latest changes on the remote
git reset --hard origin/master # will set your local branch to match the representation of the remote just pulled down.

其他答案似乎太复杂了,所以这里有一个简单的解决方案对我有效:

如何放弃所有本地更改并将文件重置为当前分支上的最后一次提交?

# Execute on the root of the working tree...

# Discard all changes to tracked files
git checkout .

# Remove all untracked files 
git clean -fd

注意:忽略的文件将不受影响

简单地执行-

git stash

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

git stash apply 

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

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