如何在不丢失 Git 中最后一次提交的情况下返回上一次提交?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15329028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to go back to previous commit without losing last commit in Git?
提问by yarun can
Here is what I want to do. I want to go back to 2 commits before, bring back the files that changed in that commit as a new commit maybe. But I do not want to lose my last commit. My last commit has some mistakes in the code but I would like to keep that one for now.
这是我想要做的。我想回到之前的 2 次提交,将在该提交中更改的文件作为新提交带回来。但我不想丢失我的最后一次提交。我的最后一次提交在代码中存在一些错误,但我现在想保留那个错误。
I read some documentation but none made it clear about what happens when you reset your head. Do you lose all the commits up until the one that you are resetting to (going backward) for example?
我阅读了一些文档,但没有人明确说明重置头部时会发生什么。例如,您是否会丢失所有提交,直到您重置为(向后)提交?
I am trying to understand how all this works but I am rather confused about git revert
, reset
and checkout
commands.
我想了解这一切工作,但我相当困惑大约GIT中revert
,reset
并checkout
命令。
I realize that I should have stashed the last commit instead of committing, but that is another story for now.
我意识到我应该隐藏最后一次提交而不是提交,但现在这是另一个故事。
采纳答案by wRAR
revert
makes a new commit that reverts changes made by an older commit. reset --hard
changes the HEAD of the current branch to the specified commit. checkout
switches the working copy to the specified branch or commit.
revert
进行新的提交以恢复旧提交所做的更改。reset --hard
将当前分支的 HEAD 更改为指定的提交。checkout
将工作副本切换到指定的分支或提交。
When you reset a branch to an older commit the newer commits are lost if they are not parts of other branches or ancestors of tags (they are still accessible via reflog
though).
当您将分支重置为较旧的提交时,如果较新的提交不是其他分支的一部分或标签的祖先(但仍可通过它们访问reflog
),则会丢失。
It is not clear what do you need to do, the most probable solutions are revert
(to fully revert an older commit or series of commits) and rebase -i
(to change an older commit or delete it from the history).
目前尚不清楚您需要做什么,最可能的解决方案是revert
(完全还原较旧的提交或一系列提交)和rebase -i
(更改较旧的提交或将其从历史记录中删除)。
回答by vonbrand
If you want to go back, say 2 commits previous, you can just do git checkout HEAD~2
. This will get you all as it was then. If you were on branch master
, git checkout master
will bring you back to the present. If, however, you want to keep the current state but start a new developemnt branch there, git checkout -b HEAD~2
will start a new branch there. In case you want to rewind master but not loose your current, unfinished/broken work, do
如果你想回去,说 2 次之前提交,你可以只做git checkout HEAD~2
. 这会让你像那时一样。如果你在分行master
,git checkout master
会带你回到现在。但是,如果您想保持当前状态但在那里启动一个新的 developemnt 分支,git checkout -b HEAD~2
则会在那里启动一个新分支。如果您想倒带母版但不想丢失当前的未完成/损坏的工作,请执行
git branch wip # New branch ends a current tip
git reset --hard HEAD~2 # Old branch rewound, get files from then