git 重置而不丢失已提交的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11482180/
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
Reset without losing already committed files
提问by cherrun
When I accidentally committed a file to the wrong branch, I normally use git reset --hard HEAD~1
. However, using this method I generally lose all the files committed. Is there a way to reset a commit, without losing the edited files?
当我不小心将文件提交到错误的分支时,我通常使用git reset --hard HEAD~1
. 但是,使用这种方法我通常会丢失所有提交的文件。有没有办法在不丢失编辑过的文件的情况下重置提交?
回答by Alex
do not use --hard
use --soft
instead.
不要使用--hard
use--soft
代替。
Thus if you want to remove your latest commit you'd do:
因此,如果您想删除最新的提交,您可以这样做:
git reset --soft HEAD^
git reset --soft HEAD^
回答by Seth Robertson
While Alex is very correct, I might be tempted to try a different sequence:
虽然亚历克斯非常正确,但我可能会尝试不同的顺序:
If I wanted the commit on a yet-to-be-born branch:
如果我想在尚未出生的分支上提交:
git branch newbranch
git reset --hard HEAD^
If I wanted the commit on an existing branch:
如果我想在现有分支上提交:
git checkout otherbranch
git cherry-pick firstbranch
git checkout firstbranch
git reset --hard HEAD^
The full example of Alex's answer
亚历克斯回答的完整示例
git reset --soft HEAD^
git checkout otherbranch
git commit -am "Message"
Note the last example will fail poorly if the attempt to "float" the change to the other branch fails due to conflicts. You will then need to stash/checkout/apply to get into conflict resolution.
请注意,如果由于冲突而将更改“浮动”到另一个分支的尝试失败,则最后一个示例将失败。然后,您需要存储/结帐/申请以解决冲突。
回答by el hafizh hidayat
for my case, i prefer using --mixed
instead, after i found this simple explanation
就我而言,--mixed
在找到这个简单的解释后,我更喜欢使用
git reset --mixed HEAD^