【问题标题】:Git undo changes in some files [duplicate]Git撤消某些文件中的更改[重复]
【发布时间】:2026-02-07 23:15:01
【问题描述】:

在编码时,我将打印语句添加到一些文件中以跟踪正在发生的事情。

完成后,是否可以恢复某些文件中的更改,但提交我实际处理的文件?

假设我在文件A 中添加了打印,但我修改了文件BB 是我想要提交的,A,我想要恢复到原来的状态。

【问题讨论】:

标签: git file version-control undo revert


【解决方案1】:

根据您对文件 A 所做的更改,有三种基本方法可以做到这一点。如果您尚未将更改添加到索引或提交它们,那么您只需使用 checkout 命令 -这将更改工作副本的状态以匹配存储库:

git checkout A

如果您已经将其添加到索引中,请使用重置:

git reset A

如果你已经提交了,那么你使用 revert 命令:

# the -n means, do not commit the revert yet
git revert -n <sha1>
# now make sure we are just going to commit the revert to A
git reset B
git commit

另一方面,如果您已经提交了它,但提交涉及的文件相当多,您也不想恢复,那么上述方法可能涉及很多“重置 B”命令。在这种情况下,您可能希望使用此方法:

# revert, but do not commit yet
git revert -n <sha1>
# clean all the changes from the index
git reset
# now just add A
git add A
git commit

又是另一种方法,需要使用 rebase -i 命令。如果您有多个要编辑的提交,这可能会很有用:

# use rebase -i to cherry pick the commit you want to edit
# specify the sha1 of the commit before the one you want to edit
# you get an editor with a file and a bunch of lines starting with "pick"
# change the one(s) you want to edit to "edit" and then save the file
git rebase -i <sha1>
# now you enter a loop, for each commit you set as "edit", you get to basically redo that commit from scratch
# assume we just picked the one commit with the erroneous A commit
git reset A
git commit --amend
# go back to the start of the loop
git rebase --continue

【讨论】:

  • 注意:revert 确实恢复了所有提交,所以这可能意味着很多“reset B”,不是吗?请参阅 gitready.com/intermediate/2009/03/16/… 的最后一个 cmets。 (如*.com/questions/642264/… 中所述,“负合并”可能更准确)。
  • 是的,如果您有很多文件被修改为提交的一部分,您不想恢复,那么需要另一种方法,我将对其进行编辑以建议一个
  • “git reset A”等价于“git checkout HEAD A”。
  • 在 GitGUI 中是否有一个快速简单的点击可以将文件恢复到存储库中的内容?使用 Git bash 工作......但如果我可以点击它会更快:-)
  • 谢谢你,你救了我的命!
【解决方案2】:

来源:http://git-scm.com/book/en/Git-Basics-Undoing-Things

git checkout -- modifiedfile.java


1)$ git 状态

你会看到修改后的文件

2)$git checkout -- modifiedfile.java

3)$git 状态

【讨论】:

  • git checkout -- modifiedfile.java 是一个不错的提示。谢谢
  • git checkout 完成了这项工作,谢谢!
【解决方案3】:
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index

【讨论】:

    【解决方案4】:

    man git-checkout:git checkout A

    【讨论】:

    • RTFM 不是一个好的答案。 git checkout A 会报错
    【解决方案5】:

    是的;

    git commit FILE
    

    将只提交 FILE。然后就可以使用了

    git reset --hard
    

    撤消其他文件中的本地更改。

    可能还有其他我不知道的方法......

    编辑:或者,正如 NicDumZ 所说,git-checkout 只是您要撤消更改的文件(最佳解决方案取决于是否有更多文件要提交或更多文件要撤消:-)

    【讨论】:

      【解决方案6】:

      您为什么不能简单地使用“git add ”(甚至“git add --interactive”或“git gui ”,其中有交互式提交的选项),然后使用“git commit”而不是“git commit -a”?

      在您的情况下(以您为例),它将是:

      prompt> git add B
      prompt> git commit
      

      只会提交对文件 B 的更改,而文件 A 将保持“脏”状态,即在工作区版本中使用这些打印语句。当你想删除那些打印语句时,使用它就足够了

      prompt> git reset A
      

      prompt> git checkout HEAD -- A
      

      恢复到提交的版本(来自 HEAD 的版本,即“git show HEAD:A”版本)。

      【讨论】: