2011-01-31 89 views
427

我的问题我已经改变了文件,例如:README,增加了新的线路“这对我的测试线”并保存该文件,然后我发出以下命令如何取消本地git的承诺

git status 

# On branch master 
# Changed but not updated: 
# (use "git add <file>..." to update what will be committed) 
# (use "git checkout -- <file>..." to discard changes in working directory) 
# 
# modified: README 
# 
no changes added to commit (use "git add" and/or "git commit -a") 


git add README 

git commit -a -m 'To add new line to readme' 

我没有把代码推到github上,现在我想取消这个提交。

为此,我使用

git reset --hard HEAD~1 

但我失去了新添加的行“这对我的测试线”自述文件。 这不应该发生。我需要内容在那里。 有没有办法保留内容并取消我的本地提交?

+1

这听起来像你绝对不会要求`git revert`,它会使用恢复的提交的反向差异创建一个新的提交。重置只是将您当前的分支指向不同的提交,在这种情况下,您希望“忘记”提交之前的提交。 – Cascabel 2011-01-31 16:11:10

+1

注意:可能值得一提的是,如果您将消息留空,`git-commit`可以中止,因此如果您没有实际完成可能有用的提交。 – GKFX 2014-02-24 17:08:36

回答

817

只需使用git reset没有--hard标志:

git reset HEAD~1 

PS:在基于Unix的系统,你可以使用HEAD^等于HEAD~1。在Windows上,HEAD^将不起作用,因为^表示续行。所以你的命令提示符会问你More?

+0

Thanks dude .. :) – 2011-01-31 12:22:54

+8

顺便说一句,这叫做`--mixed` [在手册中](http://www.kernel.org/pub/software/scm/git/docs/git-reset。 HTML#_description)。 – 2011-01-31 17:58:43

95

使用--soft代替--hard标志:

git reset --soft HEAD^ 
15

如果在中间是一个承诺(即在编辑器的话),你可以通过删除第一#上述所有行取消。这将中止提交。

所以,你可以删除所有线,从而使提交信息为空,然后保存文件:

It should look like this.

然后你会得到一个消息,说Aborting commit due to empty commit message.