【发布时间】:2026-02-07 23:15:01
【问题描述】:
在编码时,我将打印语句添加到一些文件中以跟踪正在发生的事情。
完成后,是否可以恢复某些文件中的更改,但提交我实际处理的文件?
假设我在文件A 中添加了打印,但我修改了文件B。 B 是我想要提交的,A,我想要恢复到原来的状态。
【问题讨论】:
标签: git file version-control undo revert
在编码时,我将打印语句添加到一些文件中以跟踪正在发生的事情。
完成后,是否可以恢复某些文件中的更改,但提交我实际处理的文件?
假设我在文件A 中添加了打印,但我修改了文件B。 B 是我想要提交的,A,我想要恢复到原来的状态。
【问题讨论】:
标签: git file version-control undo revert
根据您对文件 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
【讨论】:
来源: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 完成了这项工作,谢谢!
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
【讨论】:
man git-checkout:git checkout A
【讨论】:
是的;
git commit FILE
将只提交 FILE。然后就可以使用了
git reset --hard
撤消其他文件中的本地更改。
可能还有其他我不知道的方法......
编辑:或者,正如 NicDumZ 所说,git-checkout 只是您要撤消更改的文件(最佳解决方案取决于是否有更多文件要提交或更多文件要撤消:-)
【讨论】:
您为什么不能简单地使用“git add
在您的情况下(以您为例),它将是:
prompt> git add B
prompt> git commit
只会提交对文件 B 的更改,而文件 A 将保持“脏”状态,即在工作区版本中使用这些打印语句。当你想删除那些打印语句时,使用它就足够了
prompt> git reset A
或
prompt> git checkout HEAD -- A
恢复到提交的版本(来自 HEAD 的版本,即“git show HEAD:A”版本)。
【讨论】: